2
\$\begingroup\$

Already many days I'm documenting about the SQL Injection. I was wondering if the code I wrote is vulnerable in some of its parts.

<?php
if($_POST['nameone'] AND $_POST['nametwo'])
{
   $conn = new PDO("mysql:host=localhost;dbname=dbname;charset=utf8", 'dbuser', 'dbpass');
   mysql_query('SET NAMES utf8');
   $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
   $stmt = $conn->prepare("INSERT INTO `test_PDO`(`nameone`, `nametwo`) VALUES (:nomeone,:nometwo)");
   $nameone = $_POST['nameone'];
   $nametwo = $_POST['nametwo'];
   $stmt->bindParam(':nomeone', $nameone);
   $stmt->bindParam(':nometwo', $nametwo);
   $stmt->execute();
   echo "New records created successfully $nameone -- $nametwo";
   $conn = null;
}
?>

<form method="POST">
  Name one: <input type="text" name="nameone"><br>
  Name two: <input type="text" name="nametwo"><br>
  <input type="submit">
</form>

It would be great if somebody could review and confirm that this code is indeed not vulnerable to SQL injection. Or if it is vulnerable, kindly point out where, and how to make it better.

\$\endgroup\$
3
\$\begingroup\$

No, it's not vulnerable to SQL Injection, as you use prepared statements, and you use them correctly.

If you don't have any CSRF protection it is however vulnerable to XSS because of the echo (and of course CSRF), but I'm assuming that that's more of a debug statements.

Misc

  • You don't really need the variables nameone and nametwo. One-time variables are only useful if you need to give them some name to increase readability.
  • You shouldn't use mysql_*. So if you want to set the character set you should use PDO (you can also pass it as optional MYSQL_ATTR_INIT_COMMAND parameter when initializing the connection, see eg here).
  • try to be consistent with your names (nome vs name).
  • use camelCase to make your names easier to read (nameone -> nameOne).
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.