Return to Snippet

Revision: 11102
at January 23, 2009 22:21 by fackz


Initial Code
1. function sanitize($data)  
   2. {  
   3. // remove whitespaces (not a must though)  
   4. $data = trim($data);   
   5.   
   6. // apply stripslashes if magic_quotes_gpc is enabled  
   7. if(get_magic_quotes_gpc())  
   8. {  
   9. $data = stripslashes($data);  
  10. }  
  11.   
  12. // a mySQL connection is required before using this function  
  13. $data = mysql_real_escape_string($data);  
  14.   
  15. return $data;  
  16. }

Initial URL


Initial Description
This is a simple function that sanitizes the data before sending it to MySQL. First it removes whitespaces from the beginning and ending of the string. If magic_quotes_gpc is enabled and the data has been already escaped we will apply stripslashes() to the data. This way the data won’t be escaped twice when mysql_real_escape_string() is called.

Example:
$username = sanitize($_POST['username']);  
$password = sanitize($_POST['password']);

Initial Title
Sanitize data to prevent SQL Injection Attacks

Initial Tags


Initial Language
PHP