note 100854 deleted from function.mysql-real-escape-string by philip

From: Date: Fri, 04 Sep 2015 20:40:03 +0000
Subject: note 100854 deleted from function.mysql-real-escape-string by philip
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-203680@lists.php.net to get a copy of this message
Note Submitter: Anonymous ---- calling this function twice, or on a string for which quotes have already been escaped, causes the quotes to be escaped twice.An example is where we have to check for magic_quotes_gpc before calling mysql_escape_string to sanitize the inputs. The following function can be used to escape singe and double quotes in a string with out the risk of escaping quotes twice.This function escapes a quote, only if it hasn't already been escaped. <?php function safe_string_escape($str) { $len=strlen($str); $escapeCount=0; $targetString=''; for($offset=0;$offset<$len;$offset++) { switch($c=$str{$offset}) { case "'": // Escapes this quote only if its not preceded by an unescaped backslash if($escapeCount % 2 == 0) $targetString.="\\"; $escapeCount=0; $targetString.=$c; break; case '"': // Escapes this quote only if its not preceded by an unescaped backslash if($escapeCount % 2 == 0) $targetString.="\\"; $escapeCount=0; $targetString.=$c; break; case '\\': $escapeCount++; $targetString.=$c; break; default: $escapeCount=0; $targetString.=$c; } } return $targetString; } echo safe_string_escape("asda'sda\'dsad\"sadasd'"); ?> above code echoes asda\'sda\'dsad\"sadasd\' You can see that the second single quote wasnt escaped again..

« previous php.notes (#203680) next »