I am putting this up as a quick elaboration on a post I just read via Digg about You, Me and PHP and SQL injection. I am currently working with MS SQL (that is on the major project I’m doing at the moment), but my real passion lies with MySQL. Let’s face it, you do not get what you pay for with MS SQL (IMHO). To protect from unscrupulous sorts who might like to inject a bit of SQL fun I employ my handy dandy escape function, which funnily enough is named escape(). It takes a query string ala PDO prepare (SELECT * FROM User WHERE ID = ‘?’), and replaces all the wildcards with the remaining arguments that are passed to it. $query = $this->escape("SELECT * FROM User WHERE ID = '?'", $id); The only real addition/change from the way prepare syntax works is that it also has a ‘!’ wildcard, which is used when you have a nullable field which you won’t to be explicitly set to NULL if empty as opposed to ”. The function it’s self is devilishly simple, and just walks the string applying the desired escape function.

 function escape() { if (func_num_args() < 1) { return; } $lookFrom = 0; $query = func_get_arg(0); $args = array(); for ($i = 1;$i<func_num_args();$i++) { $arg = func_get_arg($i); if (get_magic_quotes_gpc() == 1) { $arg = stripslashes($arg); } //$arg = addslashes($arg); MYSQL $arg = str_replace("'","''",$arg); $pos = (strpos($query,'?',$lookFrom) >= 0) ? strpos($query,’?',$lookFrom) :NULL; $amnt = 1; if (strpos($query,’!',$lookFrom) >= 0 && (strpos($query,’!',$lookFrom) < $pos || $pos == NULL) && is_int(strpos($query,'!',$lookFrom))) { $pos = strpos($query,'!',$lookFrom); if ($arg == '') { $arg = 'NULL'; $pos--; $amnt = 3; } } $query = substr_replace($query,$arg,$pos,$amnt); $lookFrom = $pos + strlen($arg); } return $query; }  

As you can see it peruses the string for the characters to replace until all the arguments are used. It has no error checking as the onus is on you as the user to pass the right number of arguments, but it provides a one stop shop for replacing.

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • DZone
  • Slashdot

  • BROWSE / IN

SPEAK / ADD YOUR COMMENT
Comments are moderated.

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Return to Top