I want to make my code as safe as possible from any type of attack I was hoping for some insight on the simple code I am using below. Any pointers on how to make it safer if it is vulnerable and why would be awesome. I have read that using prepared statements is the best practice to safeguard against attacks.
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=test', 'user', 'XXXXX');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('INSERT INTO people (name, email) VALUES (:name, :email)');
$stmt->execute(array(':name' => $_POST['name'], ':email' => $_POST['email']));
#If one or more rows were returned...
} catch(PDOException $e){
echo'ERROR: ' . $e->getMessage();
}
echo "Added $_POST[name] with email $_POST[email] succsessfully";
$conn = null;
?>
It looks like you’re safe from SQL injection, but you now have issues with XSS in your echo. Make sure you always sanitize / escape user input before its echo’d.
should become