Search code examples
phpsecuritymysql-real-escape-string

My function vs Mysql_real_escape_string


I have sessions that for the website and this is how i use them:

   $username = CleanMe($_SESSION["username"]);
   $password = CleanMe($_SESSION["password"]);

   //return clean values
   $_SESSION["username"] = $username;
   $_SESSION["password"] = $password;

CleanMe is:

       function CleanMe($strWords){ 
       $bad_string = array("select", "drop", ";", "--", "insert","delete", 
       "xp_", "%20union%20", "/*", "*/union/*", "+union+", "load_file", 
       "outfile", "document.cookie", "onmouse", "<script", "<iframe", "<applet", 
       "<meta", "<style", "<form", "<img", "<body", "<link", "_GLOBALS", "_REQUEST", 
       "_GET", "_POST", "include_path", "prefix", "http://", "https://", 
       "ftp://", "smb://", "'", "\""); 
       for ($i = 0; $i < count($bad_string); $i++){ 
       $strWords = str_replace ($bad_string[$i], "", $strWords); 
       } 
       return $strWords; 
       }

Now, does it make sense for me to use mysql_real_escape_string or what i have, CleanMe is more secure?


Solution

  • Just reuse existing functions as much as possible; mysql_real_escape_string in this case. It's pretty likely that you forgot something in CleanMe which makes it insecure. You only need to forget one string to make it insecure and you may not know what that string is now.

    Just remember: an attacker has enough time and has to get it right only once but a developer needs to be right every time. So the lesson is: don't make it harder for yourself and use and apply existing functions properly.