Posted By

halk on 10/14/12


Tagged

mysqlinjectionxssescapesanitize


Versions (?)

MySql Safe Escape (single var,array,md-array)vs Injection XSS


 / Published in: PHP
 

This is my function for sanitizing data before I insert it into my database. It handles single variables, single dimensional arrays, and multi-dimensional arrays(recursive). It sanitizes numeric data(detects if int or float), checks for html tags in the posted data and makes it safe for storage(I store html and code snippets in my db). It checks for magic quotes and determines if mysqlrealescapestring function exists and if it doesnt mysqlescape_string is used (for older versions of php).

  1. /**
  2.   * UTILITY FUNCTION WHICH CLEANS VARIABLES PASSED TO IT FOR STORAGE
  3.   * IN A MYSQL DATABASE. INCLUDES SECURITY MEASURES FOR SQL INJECTION
  4.   * AND XSS CROSS SITE SCRIPTING. (HANDLES SINGLE VARIABLES, ARRAYS AND
  5.   * MULTI-DIMENSIONAL ARRAYS THRU DETECTING VARIABLE TYPE PASSED IN)
  6.   */
  7. function safe_escape($data){
  8. //CHECK IF THE DATA PASSED IS AN ARRAY. IF IT IS CALL THIS FUNCTION RECURSIVELY
  9. //ON EACH ELEMENT IN THE ARRAY
  10. if(is_array($data)){
  11. foreach($data as $key => $value){
  12. $data[$key] = safe_escape($data[$key]); //RECURSIVE CALL FOR EACH ELEMENT IN THE ARRAY
  13. }
  14.  
  15. }//ELSE IF THE DATA IS NOT AN ARRAY WE ALLOW THE REST OF THE FUNCTION TO EXECUTE
  16. //BEGIN SANITIZATION OF DATA FOR INSERT
  17. $data = trim($data); //TRIM LEADING AND TRAILING SPACES (THIS IS NOT ESSENTIAL!)
  18. if (get_magic_quotes_gpc()){ //IF MAGIC QUOTES IS ON STRIP ALL SLASHES FROM THE DATA
  19. $data = stripslashes($data);
  20. }
  21. //IF THE DATA IS NUMERIC
  22. if(is_numeric($data)){
  23. if(is_int($data)){
  24. //IF THE DATA IS AN INTEGER(WHOLE NUMBER)
  25. $data = filter_var($data,FILTER_SANITIZE_NUMBER_INT);
  26. return $data;
  27. }
  28. if(is_float($data)){
  29. //IF THE DATA IS A FLOATING POINT NUMBER(DECIMAL)
  30. $data = filter_var($data,FILTER_SANITIZE_NUMBER_FLOAT);
  31. return $data;
  32. }
  33. } //ELSE THE DATA IS NOT NUMERIC AND THE REST OF THE SCRIPT EXECUTES
  34. //CHECK FOR THE EXISTENCE OF HTML TAGS IN THE DATA
  35. if($data != strip_tags($data)) { //IF THE DATA DOES NOT EQUAL ITSELF AFTER TAGS ARE STRIPPED
  36. // THEN IT CONTAINS HTML DATA WE WILL RUN HTMLENTITIES ON IT
  37. $data = htmlentities($data); //THIS HELPS PREVENT XSS ATTACKS (CROSS SITE SCRIPTING)
  38. }
  39. //CHECK IF THE RUNNING PHP ENVIRONMENT HAS MYSQL_REAL_ESCAPE_STRING() FUNCTION
  40. if (function_exists('mysql_real_escape_string')) {
  41. return mysql_real_escape_string($data);
  42. }
  43. else { //OLDER VERSIONS OF PHP MUST USE THIS FUNCTION(@ TO SQUELCH DEPRICATION ERRORS)
  44. return @mysql_escape_string($data);
  45. }
  46. }//END OF safe_escape FUNCTION

Report this snippet  

You need to login to post a comment.