/ 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 mysql_real_escape_string function exists and if it doesnt mysql_escape_string is used (for older versions of php).
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/** * 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 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 } //IF THE DATA IS NUMERIC //IF THE DATA IS AN INTEGER(WHOLE NUMBER) return $data; } //IF THE DATA IS A FLOATING POINT NUMBER(DECIMAL) 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 // THEN IT CONTAINS HTML DATA WE WILL RUN HTMLENTITIES ON IT } //CHECK IF THE RUNNING PHP ENVIRONMENT HAS MYSQL_REAL_ESCAPE_STRING() FUNCTION } else { //OLDER VERSIONS OF PHP MUST USE THIS FUNCTION(@ TO SQUELCH DEPRICATION ERRORS) } }//END OF safe_escape FUNCTION