note 100853 deleted from function.mysql-escape-string by danbrown

From: Date: Thu, 11 Nov 2010 16:33:43 +0000
Subject: note 100853 deleted from function.mysql-escape-string by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-173947@lists.php.net to get a copy of this message
Note Submitter: sandeepicq at gmail dot com ---- 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. 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("asdasda'dsad\"sadasd'");

« previous php.notes (#173947) next »