Posted By

wbowers on 03/09/08


Tagged

escape sql php injection safe xss


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

SpinZ
sonix
eunjoo1984
vali29


PHP escape for SQL


 / Published in: PHP
 

URL: http://www.roscripts.com/snippets/show/157

  1. /**
  2.  * Correctly quotes a string so that all strings are escaped. We prefix and append
  3.  * to the string single-quotes.
  4.  * An example is escape ( "Don't bother",magic_quotes_runtime () );
  5.  *
  6.  * @param str the string to quote
  7.  * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
  8.  *
  9.  * @return quoted string to be sent back to database
  10. */
  11. function escape ( $str, $magic_quotes = false )
  12. {
  13. switch ( gettype ( $str ) )
  14. {
  15. case 'string' :
  16. $replaceQuote = "\\'"; /// string to use to replace quotes
  17. if ( ! $magic_quotes ) {
  18.  
  19. if ( $replaceQuote [ 0 ] == '\\' ){
  20. // only since php 4.0.5
  21. $str = seo_str_replace ( array ( '\\', "\0" ), array ( '\\\\', "\\\0" ), $str );
  22. //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
  23. }
  24. return "'" . str_replace ( "'", $replaceQuote, $str ) . "'";
  25. }
  26.  
  27. // undo magic quotes for "
  28. $str = str_replace ( '\\"','"', $str );
  29.  
  30. if ( $replaceQuote == "\\'" ) {// ' already quoted, no need to change anything
  31. return "'$str'";
  32. }
  33. else {// change \' to '' for sybase/mssql
  34. $str = str_replace ( '\\\\','\\', $str );
  35. return "'" . str_replace ( "\\'", $treplaceQuote, $str ) . "'";
  36. }
  37. break;
  38. case 'boolean' : $str = ($str === FALSE) ? 0 : 1;
  39. return $str;
  40. break;
  41. case 'integer' : $str = ($str === NULL) ? 'NULL' : $str;
  42. return $str;
  43. break;
  44. default : $str = ($str === NULL) ? 'NULL' : $str;
  45. return $str;
  46. break;
  47. }
  48. }

Report this snippet  

You need to login to post a comment.