0

The most common suggestion for protection against MySQL injection is prepared statements (either from PDO of mysqli). Say for whatever reason, I can't use prepared statemnets...how do I protect my data?

I would love to create a function like the following...

function cleanse($val) {
   global $db;
   $val = $db->real_escape_string($val);
   return $val;
}

//Then I use it like
$sql = "select abc from dyf where z='".cleanse($_GET['id'])."'";
$db->query($sql); //etc...

But I'm not sure if that stops 1=1 attacks and attacks from strange foreign characters.

Is there a bullet proof way to make my cleanse function secure (no prepared functions!)?

Do I need to convert any string to utf-8?

If I wrap all column values in quotes and use mysqli's real_escape_string, am I ok?

Are there any other tricks that would make my cleanse function safe against injection?

user2662680
  • 677
  • 8
  • 16
  • 2
    Possible duplicate of [How can I prevent SQL-injection in PHP?](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Kostas Mitsarakis Nov 12 '15 at 23:14
  • 4
    why would you even think of that? you plan on ignoring the tools made available to you and re-invent the wheel? – Funk Forty Niner Nov 12 '15 at 23:15
  • Why would you want to do this? And why are you using "globals" in 2015? – Zarathuztra Nov 12 '15 at 23:19
  • 1
    mysqli_real_escape string is not meant to be a security feature. It is simply there to ensure that the data you send to the MySQL server is in the correct format (or as the manual calls it, "legal"). The process of escaping does, as an aside, prevent several potential exploits, but they should not be your only consideration. – rjdown Nov 12 '15 at 23:25

1 Answers1

1

I won't recommend it, but using mysql_real_escape_string can do the trick.

$sql = "select abc from dyf where z='".mysql_real_escape_string($_GET['id'])."'";

But if you can use PDO use it anyday, if you are limited this would be an oportunity. Only works in some versions of PHP.

http://php.net/manual/en/function.mysql-real-escape-string.php

mrhn
  • 17,961
  • 4
  • 27
  • 46