简体   繁体   中英

Why isn't PHP PDO protecting my query from injection?

I'm still in the progress of learning PDO fully, but I was kind of surprised when I checked this evening if it worked to SQL Inject the URL parameter, and to my surprise, it did work. So I started thinking; the posted values are supposed to be sanitized automatically using PDO - prepared statements, which means there must be something wrong with my SQL query, am I right?

I'm having a page that needs a GET variable in order to gather corresponding data from my database with that ID. I have created a function that includes preparing the query, and as well as executing it to simplify the coding process. The code I have written now looks like:

 $request = $_GET['movie'];
 $sql = "SELECT * FROM `movies` WHERE `url` = '$request'";
 $db = new database;
 $db->setDBC();

 $process = $db->executeQuery($sql);
 $cmd = $process->fetch(PDO::FETCH_NUM);

 $title = $cmd[1];

And the PDO Exception I get is:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''21-31282 ''' at line 1' in C:\\xampp\\htdocs\\filmvote\\include\\databaseClass.php:33 Stack trace: #0 C:\\xampp\\htdocs\\filmvote\\include\\databaseClass.php(33): PDOStatement->execute() #1 C:\\xampp\\htdocs\\filmvote\\recension.php(9): databaseManagement->executeQuery('SELECT * FROM `...') #2 {main} thrown in C:\\xampp\\htdocs\\filmvote\\include\\databaseClass.php on line 33

You get this kind of error when adding ' or 1-1 to the URL. What can I do about this? Really grateful for help.

the posted values are supposed to be sanitized automatically using PDO

Nope. Only if you use actual prepared statements like so:

$stmt = $dbh->prepare("SELECT * FROM `movies` WHERE `url` = ?");
if ($stmt->execute(array($_GET['movie'])))  // <-- This sanitizes the value
  { 
    // do stuff
  }

will your the values you insert be automatically sanitized, and your query protected from SQL injection.

Otherwise, your SQL query will be executed like any old mysql_query() , and is vulnerable. PDO can not take a query and then automatically sanitize the vulnerable parts. That's not possible.

Try prepared statements:

$query = $db->prepare("SELECT * FROM `movies` WHERE url = ?");
$query->execute(array($request));
$result = $query->fetch(PDO::FETCH_ASSOC);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM