Skip to main content
2 of 2
added 81 characters in body
omyzach
  • 95
  • 1
  • 5

How can I make this code safer against XSS attacks?

I'm not sure what I'm doing wrong, but I run the code using a Web Vulnerability software and I get a lot of XSS attacks against the code. Is there something I could do better? <?php

// connect to database
include("dbconnect.php");

$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$category = $_POST['category'];

$add = $db->prepare("INSERT INTO contacts SET firstName=(?), lastName=(?), email=(?), phone=(?), category=(?)");
$add->bind_param('sssss', $firstName, $lastName, $email, $phone, $category);

$firstName = $db->real_escape_string($firstName);
$lastName = $db->real_escape_string($lastName);
$email = $db->real_escape_string($email);
$phone = $db->real_escape_string($phone);
$category = $db->real_escape_string($category);

$add->execute();
$add->close();
header("Location:http://localhost/address-book/contact.php");
exit;

?>

Everything works great, but I'm wonder if there's a safer way to go about it.

I wrote it as prepared statements and ran each variable through mysqli_real_escape_string hoping to strip most of the nasty things. But, no lucky.

I'm new to PHP, so this is all a bit alien to me.

omyzach
  • 95
  • 1
  • 5