0

I'm attempting to create a simple php page that demonstrates SQL injection.

<?php
  ...

  if ($_POST) {
    $user = $_POST['user'];

    if ($result = $db->query("SELECT * FROM users WHERE username ='" . $user . "'")) {
      // display result array
    } else {
      // invalid query
    }
  }

  ...
?>

The code I am injecting into the html input is whatever" OR 1=1; DROP TABLE users; -- but it always triggers the invalid query block. How can I trick the script into thinking this SQL is valid?

4
  • 2
    put a single quote behind whatever Commented Apr 22, 2014 at 8:25
  • This will not always not work, though, because only one query will be allowed to go through .. except for PDO_mysqlnd apparently. Commented Apr 22, 2014 at 8:26
  • mysqli::query does only execute one single statement. Commented Apr 22, 2014 at 8:27
  • 2
    First read something about sql injection Commented Apr 22, 2014 at 8:27

1 Answer 1

1

How can I trick the script into thinking this SQL is valid?

You can’t trick it into thinking it is valid SQL. You actually have to make it valid SQL.

It may help when you echo the resulting SQL statement to see the actual result:

$stmt = "SELECT * FROM users WHERE username ='" . $user . "'";
echo $stmt;
if ($result = $db->query($stmt)) {
    // …
}

Since the injection happens in a MySQL string literal, you have to provide SQL fragments that allow you to escape from that string literal. Since the string literal is enclosed within single quotes, a single single quote would denote the end delimiter and any following data is no longer interpreted as string:

user: whatever' OR '1'='1

This would result in:

SELECT * FROM users WHERE username ='whatever' OR '1'='1'
#                                    \_________________/
#                                         injected

Note that mysqli::query does only execute one single statement. That’s why the second statement causes an error. So the second DROP TABLE statement example doesn’t work here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.