Posted By

sarfraznawaz2005 on 02/07/09


Tagged

sql injection prevent


Versions (?)

Who likes this?

5 people have marked this snippet as a favorite

jfherring
FlamesOfDestiny
pezland
vali29
aleksanderek


SQL Injection


 / Published in: PHP
 

This function can be used to discard any characters that can be used to manipulate the SQL queries. So, you can use this function to validate your SQL queries against sql injection:

  1. /*
  2. I have made the following function that can be used to discard any characters that can be used to manipulate the SQL queries.
  3. So, you can use this function to validate your SQL queries against sql injection:
  4.  
  5. example use:
  6.  
  7. if (is_valid($_REQUEST["username"]) == true && is_valid($_REQUEST["pass"]) == true)
  8. {
  9.   //login now
  10. }
  11.  
  12.  
  13. You should still use mysql_real_escape_string() function in your queries to be
  14. MORE secure.
  15.  
  16. */
  17.  
  18. function is_valid($input)
  19. {
  20. $input = strtolower($input);
  21.  
  22. if (str_word_count($input) > 1)
  23. {
  24. $loop = true;
  25. $input = explode(" ",$input);
  26. }
  27.  
  28. $bad_strings array("'","--","select","union","insert","update","like","delete","1=1","or");
  29.  
  30. if ($loop == true)
  31. {
  32. foreach($input as $value)
  33. {
  34. if (in_array($value,$bad_strings))
  35. {
  36. return false;
  37. }
  38. else
  39. {
  40. return true;
  41. }
  42. }
  43. }
  44. else
  45. {
  46. if (in_array($input,$bad_strings))
  47. {
  48. return false;
  49. }
  50. else
  51. {
  52. return true;
  53. }
  54. }
  55. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: MMDeveloper on February 20, 2009

wouldn't be too helpful for anyone wanting to allow text comments, emails etc... I used the words "like" "or", "update" and "union" all the time.

Just run your text input through mysqlrealescape_string() (if using mysql)

OR

if you are using mysqli in it's native OOP construct, run all your inputs through mysqli's escape method

[code] $mysqli = new mysqli("localhost", "myuser", "mypassword", "world"); $city = $mysqli->realescapestring($city); [/code]

that will escape the characters needed to break the SQL string for a SQL injection attack to take place.. for example

update users set name='$newname' where id=$id limit 1;

the $newname would need to include a single quote for the SQL engine to parse it as a command instead of a string like this

$newname = "' OR 1=1 drop table users --";

since the single quote is required... the realescapestring() would just escape that single quote and be done with it, no need to string matching and array looping that would flag a lot of false positives :P

You need to login to post a comment.