1

i am using PDO package to manage my application database. i use PDO::prepare , PDOStatement::execute and somtimes PDO::quote , PDO::query / PDO::exec to excute my queries

are PDO::prepare and PDO::quote completely secure? or shoud i make more work to properly validate my inputs.not only for databaase but for php code either Thank you

adel adl
  • 35
  • 7
  • not only injection. shouldn't i be worry about all inputs risks? – adel adl Jun 08 '17 at 22:10
  • You shouldn't trust user input, yeah. But you mentioned PDO _stuff_, so I assume that's db you're talking about. If you are going to output some info provided by users, you might also want to look into XSS (Cross-site scripting). But really, security is a long list, making this question at least _too broad_. – FirstOne Jun 08 '17 at 22:13
  • 1
    Define *secure*. – N.B. Jun 09 '17 at 06:36
  • beside database. i use PDO::quote to (clean) inputs value in order to interpolate them on php code. is that enough? – adel adl Jun 09 '17 at 14:05
  • @adeladl what would you protect against using `PDO::quote` if you're "cleaning" values that you stick in PHP, which, presumably, ends up displayed via some HTML? `PDO::quote` has its own purpose, it's to clean values which you add to **database**, not somewhere else and if you use prepared statements - cleaning is done based on connection character set - basically, you can forget about that function. You can't stick a function in and expect it makes everything safe out of the blue. Is my car faster if I paint it blue? – N.B. Jun 11 '17 at 20:51

1 Answers1

3

There's nothing magic about using prepare(). You can interpolate unsafe variables into a string and then prepare that string. Boom—SQL injection. Preparing a statement doesn't make it safe.

$stmt = $pdo->prepare("SELECT * FROM MyTable WHERE id = {$_POST['id']}"); // UNSAFE!

What makes it safe is using parameters.

$stmt = $pdo->prepare("SELECT * FROM MyTable WHERE id = ?");
$stmt->execute([$_POST['id']]); // SAFE!

Naturally, people say "use prepared statements" because you must use prepared statements to use parameters. But just saying "use prepared statements" kind of misses the point, and some developers get the wrong understanding.


The PDO quote() method is also safe, but I find it simpler and easier to use parameters.

$idQuoted = $pdo->quote($_POST['id']);
$stmt = $pdo->prepare("SELECT * FROM MyTable WHERE id = $idQuoted");
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828