Return to Snippet

Revision: 59993
at October 14, 2012 03:47 by halk


Initial Code
/**
  * UTILITY FUNCTION WHICH CLEANS VARIABLES PASSED TO IT FOR STORAGE
  * IN A MYSQL DATABASE.  INCLUDES SECURITY MEASURES FOR SQL INJECTION
  * AND XSS CROSS SITE SCRIPTING. (HANDLES SINGLE VARIABLES, ARRAYS AND
  * MULTI-DIMENSIONAL ARRAYS THRU DETECTING VARIABLE TYPE PASSED IN)
  */
 function safe_escape($data){
    //CHECK IF THE DATA PASSED IS AN ARRAY.  IF IT IS CALL THIS FUNCTION RECURSIVELY
    //ON EACH ELEMENT IN THE ARRAY
    if(is_array($data)){
        foreach($data as $key => $value){
            $data[$key] = safe_escape($data[$key]);  //RECURSIVE CALL FOR EACH ELEMENT IN THE ARRAY
        }
          
    }//ELSE IF THE DATA IS NOT AN ARRAY WE ALLOW THE REST OF THE FUNCTION TO EXECUTE
    //BEGIN SANITIZATION OF DATA FOR INSERT 
    $data = trim($data); //TRIM LEADING AND TRAILING SPACES  (THIS IS NOT ESSENTIAL!)
    if (get_magic_quotes_gpc()){ //IF MAGIC QUOTES IS ON STRIP ALL SLASHES FROM THE DATA
      $data = stripslashes($data);
    }
    //IF THE DATA IS NUMERIC
    if(is_numeric($data)){
        if(is_int($data)){
            //IF THE DATA IS AN INTEGER(WHOLE NUMBER)
            $data = filter_var($data,FILTER_SANITIZE_NUMBER_INT);
            return $data;
        }
        if(is_float($data)){
            //IF THE DATA IS A FLOATING POINT NUMBER(DECIMAL)
            $data = filter_var($data,FILTER_SANITIZE_NUMBER_FLOAT);
            return $data;
        }
    } //ELSE THE DATA IS NOT NUMERIC AND THE REST OF THE SCRIPT EXECUTES
    //CHECK FOR THE EXISTENCE OF HTML TAGS IN THE DATA
    if($data != strip_tags($data)) { //IF THE DATA DOES NOT EQUAL ITSELF AFTER TAGS ARE STRIPPED
    // THEN IT CONTAINS HTML DATA WE WILL RUN HTMLENTITIES ON IT
     $data = htmlentities($data);  //THIS HELPS PREVENT XSS ATTACKS (CROSS SITE SCRIPTING)
    }
    //CHECK IF THE RUNNING PHP ENVIRONMENT HAS MYSQL_REAL_ESCAPE_STRING() FUNCTION
    if (function_exists('mysql_real_escape_string')) {
      return mysql_real_escape_string($data);
    }
    else { //OLDER VERSIONS OF PHP MUST USE THIS FUNCTION(@ TO SQUELCH DEPRICATION ERRORS)
      return @mysql_escape_string($data);
    }
  }//END OF safe_escape FUNCTION

Initial URL

                                

Initial Description
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 mysql_real_escape_string function exists and if it doesnt mysql_escape_string is used (for older versions of php).

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

Initial Tags

                                

Initial Language
PHP