问题
I created a small PHP-script, that runs on a server with PHP 5.2.17 and the magic_quotes_gpc
directive enabled.
I have no write-access to the php.ini file, and I'd like to remove all slashes from user inputs.
This should work even if the magic_quotes_gpc
directive is turned off (for example when moving the scripts to another server).
It should also work recursively when arrays are submitted by the user.
I prefer using a built in-function.
<html>
<head>
<title>HP</title>
</head>
<body>
<form method="POST" action="magic.php">
<input type="text" value="te\\"st" name="test1">
<input type="text" value="te\\"st" name="test2[tw"o]">
<input type="submit" value="submit">
</form>
<?php
echo "<pre>";
echo "magic_quotes: ".get_magic_quotes_gpc()."\n";
echo "<hr>test1";
echo "filter_input: ".filter_input(INPUT_POST, "test1")."\n";
echo "POST: ".$_POST['test1']."\n";
echo "<hr>test2 (filter)";
print_r(filter_input_array(INPUT_POST))."\n";
echo "<hr>test2 (post)";
print_r($_POST)."\n";
echo "</pre>";
?>
</body>
</html>
Which gives the following result on my server:
magic_quotes: 1
filter_input: te\\"st
POST: te\\\\\"st
test2 (filter)Array
(
[test1] => te\\"st
[test2] => Array
(
[tw\"o] => te\\"st
)
)
test2 (post)Array
(
[test1] => te\\\\\"st
[test2] => Array
(
[tw\"o] => te\\\\\"st
)
)
It seems that except for the array keys the slashes are removed.
Or are the slashes never added? (filter_input()
and filter_input_array()
might ignore the magic_quotes_gpc
directive, since it is deprecated; but I could not find a reference for that)
Is the behaviour for removing/not setting the slashes of filter_input()
and filter_input_array()
somehow dependent on system-parameters?
I don't understand the warning here.
回答1:
I've been unsuccessful in finding it in official documentation, but the filter_input()
function operates on the raw data, and is unaffected by magic_quotes
settings. The sanitize filter, FILTER_SANITIZE_MAGIC_QUOTES
, will put them in if you need them.
It's been a boon for me personally, because I'm working in a legacy system that has magic_quotes
turned on. By using the filter_input()
function I can use the values without having to strip slashes before binding them in PDO
.
These articles talk about it:
http://www.sitepoint.com/forums/showthread.php?590848-Filter_input-magic-quotes
https://weston.ruter.net/2013/10/22/revelations-about-filter_input/
http://php.net/manual/en/function.filter-input.php#99124
回答2:
I usually use something along the following lines for normalizing input data against the magic_quotes setting.
function deslash (array $data)
{
foreach ($data as $key => $val)
{
$data [$key] = is_array ($val)? deslash ($val): stripslashes ($val);
}
return $data;
}
if ((!empty ($_POST)) && (get_magic_quotes_gpc ()))
{
$posted = deslash ($_POST);
}
来源:https://stackoverflow.com/questions/9533122/when-does-filter-input-remove-slashes-of-post-variables