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.

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Apr 11, 2016 at 17:56
\$\endgroup\$

1 Answer 1

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).
answered Apr 11, 2016 at 18:16
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.