$_POST = mysql_real_escape_string($_POST);
By executing this statement, does each post value now get escaped via mysql_real_escape_string
?
$_POST = mysql_real_escape_string($_POST);
By executing this statement, does each post value now get escaped via mysql_real_escape_string
?
No. That won't work at all: $_POST
is an array: mysql_real_escape_string
needs a string as its first argument. You can, however, achieve what you want with array_map
:
$_POST = array_map('mysql_real_escape_string', $_POST);
Or array_walk_recursive
as array_map
does not work on array post values:
array_walk_recursive($_POST, function(&$v, $k) {$v = mysql_real_escape_string($v);});
Better, however, would be to use paramaterised queries: this is by far the most secure way to avoid SQL injection. Not only does the above option do needless escaping (for instance, members of the $_POST
array that don't need to be inserted into the database), it also makes it harder to use the data in other contexts, e.g. returning them to the browser in some way.
No, but you can use array_walk()
Docs or array_walk_recursive()
Docs to achieve that, as mysql_real_escape_string()
Docs requires a string (go figure...) as input, and you're passing it an array instead.
With this, you pass each array element the same callback function:
array_walk_recursive($_POST, 'escape');
escape($k,$v)
{
return mysql_real_escape_string($v);
}
But it's better to treat each value accordingly, for ex. casting an INT to INT, etc., or better yet, use parametrized queries.
Since $_POST is an array, this will going to give you an error.
link: http://php.net/manual/en/function.mysql-real-escape-string.php
$escapedPost = array_map(array($this, 'recursive_escape'), $_POST);
/**
* recursively escape an array containing strings and/or arrays
*/
function recursive_escape($value) {
if (is_array($value)) {
array_map(array($this, 'recursive_escape'), $value);
} else {
$value = mysql_real_escape_string($value);
}
return $value;
}