note 100854 modified in function.mysql-real-escape-string by danbrown
| From: | danbrown@php.net | Date: | Thu, 11 Nov 2010 16:32:13 +0000 |
| Subject: | note 100854 modified in function.mysql-real-escape-string by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-173946@lists.php.net to get a copy of this message | ||
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..
--was--
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("asda'sda\'dsad\"sadasd'");
?>
above code echoes
asda\'sda\'dsad\"sadasd\'
You can see that the second single quote wasnt escaped again..
http://php.net/manual/en/function.mysql-real-escape-string.php