note 100854 added to function.mysql-real-escape-string

From: Date: Thu, 11 Nov 2010 05:44:37 +0000
Subject: note 100854 added to function.mysql-real-escape-string
Groups: php.notes 
Request: Send a blank email to php-notes+get-173937@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. 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.. ---- Server IP: 64.71.164.2 Probable Submitter: 66.90.104.167 ---- Manual Page -- http://www.php.net/manual/en/function.mysql-real-escape-string.php Edit -- https://master.php.net/note/edit/100854 Del: integrated -- https://master.php.net/note/delete/100854/integrated Del: useless -- https://master.php.net/note/delete/100854/useless Del: bad code -- https://master.php.net/note/delete/100854/bad+code Del: spam -- https://master.php.net/note/delete/100854/spam Del: non-english -- https://master.php.net/note/delete/100854/non-english Del: in docs -- https://master.php.net/note/delete/100854/in+docs Del: other reasons-- https://master.php.net/note/delete/100854 Reject -- https://master.php.net/note/reject/100854 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#173937) next »