1

I've read through many of the recommended questions regarding php, pdo and prepared statements, but I still find myself questioning if what I have is enough to prevent an sql injection or other attack. I have a single form that collects user emails and sends them to a table in my phpadmin database. The database connection is functional and the html form successfully sends the email input into the table, see the code below. My question is, is what I have sufficient to prevent sql attacks??

<?php
$dbHost = "";
$dbUser = "";
$dbPassword = "";
$dbName = "";

try {
  $dsn = "mysql:host=" . $dbHost . ";dbname=" . $dbName;
  $pdo = new PDO($dsn, $dbUser, $dbPassword);
} catch(PDOException $e) {
  echo "DB Connection Failed: " . $e->getMessage();
}

$status = "";
if($_SERVER['REQUEST_METHOD'] == 'GET') {
  $email = $_GET['email'];

  if(!filter_var($email, FILTER_VALIDATE_EMAIL))  {
      $status = "Please enter a valid email<br/>(no space at the end)";
    } else {

      $sql = "INSERT IGNORE INTO contactinfo (email) VALUES (:email)";

      $stmt = $pdo->prepare($sql);
      
      $stmt->execute(['email' => $email]);

      $status = "Success! Please click the confirmation link in the email I've sent you. It will expire in 12 hours.";
      $email = "";
    }
  }
?>
  • 1
    From SQL perspective, you are using a prepared statement. This is sufficient to prevent SQL injection. – GMB Sep 04 '20 at 17:00
  • 2
    Yep, looks good. However, note that you are not checking the return value of either the `prepare()` or the `execute()` calls. They could fail and return `FALSE`. – Alex Howansky Sep 04 '20 at 17:03
  • @AlexHowansky and you should never do that. Instead, you have to configure PDO to report errors automatically – Your Common Sense Sep 04 '20 at 17:07

0 Answers0