Reputation: 54016
When I write
input data: hel'l"lo
print_r($_POST)
display hel\'\"lo
and when I use
if(get_magic_quotes_gpc()){
mysql_real_escape_string($_POST);
display
hel\\\'\\\"lo
Because PHP automatically adds slashes, is it necessary to use mysql_real_escape_string
?
Upvotes: 0
Views: 2256
Reputation: 1430
magic solution found in internet honestly
if (get_magic_quotes_gpc()) {
$process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
while (list($key, $val) = each($process)) {
foreach ($val as $k => $v) {
unset($process[$key][$k]);
if (is_array($v)) {
$process[$key][stripslashes($k)] = $v;
$process[] = &$process[$key][stripslashes($k)];
} else {
$process[$key][stripslashes($k)] = stripslashes($v);
}
}
}
unset($process);
}
Upvotes: 0
Reputation: 382616
No, from version 5.3 onwards, there will be no slashes added by default. Also note that addslashes
is not a replacement for mysql_real_escape_string
; you can read more about that here.
Upvotes: 3
Reputation: 4955
I've recently used an hosting with PHP 5.3.6 with the option "magic_quotes_gpc" enabled. Unfortunately it's a shared hosting so I could not change the config (Also "php_flag magic_quotes_gpc Off" to .htaccess failed).
A code-level solution that worked for me was placing this at the beginning
if (get_magic_quotes_gpc() === 1)
{
$_GET = json_decode(stripslashes(json_encode($_GET, JSON_HEX_APOS)), true);
$_POST = json_decode(stripslashes(json_encode($_POST, JSON_HEX_APOS)), true);
$_COOKIE = json_decode(stripslashes(json_encode($_COOKIE, JSON_HEX_APOS)), true);
$_REQUEST = json_decode(stripslashes(json_encode($_REQUEST, JSON_HEX_APOS)), true);
}
See here too
http://php.net/manual/en/security.magicquotes.disabling.php
Upvotes: 0
Reputation: 536349
is it necessary to use mysql_real_escape_string?
Yes. But not as a blanket encoding over $_POST
or $_GET
. That's applying an output-stage escaping mechanism to the input stage, which is the wrong thing and will mangle your strings in unexpected and unwanted ways.
You should keep your strings in raw form up until the moment you insert the string into another context. At that point only, you use the appropriate escaping function. With MySQL:
$query= "SELECT * FROM items WHERE title='"+mysql_real_escape_string($_POST['title'])+"'";
or with HTML:
<p>Title: <?php echo(htmlspecialchars($_POST['title'])) ?></p>
Upvotes: 0