Organizational Research By

Surprising Reserch Topic

Is there a better way than mysql_real_escape_string() to filter variables from clients in PHP?


On a PHP file, I receives more than 20 variables coming from the client(submitted via a web form) and I have to apply mysql_real_escape_string() more than 20 times, it is quite troublesome, is there a better way to do this job?


asked May 8, 2015 in PHP by rajesh
0 votes
44 views



Related Hot Questions

3 Answers

0 votes

you can use array_map also

$_POST = array_map('mysql_real_escape_string',$_POST);
answered May 8, 2015 by rajesh
0 votes

No, that is the best way. As answered in this old question, you should always use whatever tools the language/system has available for you.

However, your issue still remains about it being tedious. I'd suggest a loop. Assuming your variables are in $_POST:

$vars = array("foo", "bar", "baz"); // names of variables
foreach ($vars as $var) {
    // tricky $$ usage will create the variables
    // $foo, $bar, etc., with the escaped values.
    ${$var} = mysql_real_escape_string($_POST[$var]);
    // you could also store an array of inputs, like $inputs[$var] = ...;
}
answered May 8, 2015 by rajesh
0 votes

I would prefer prepared queries via DBO.. but here's an option

function recursive_escape($arrayin) {
    if (is_array($arrayin)){
        foreach($arrayin as $key=>$value){
            if (is_array($value)){
                foreach($value as $key2=>$value2){
                    $escapedArray[$key][$key2] = mysql_real_escape_string($value2);
                }
            } else {
                $escapedArray[$key] = mysql_real_escape_string($value);
            }
        }
    } else {
        //nothing done
        $escapedArray = $arrayin;
    }
    if(!isset($escapedArray)) {
        $escapedArray = Array ( );
    }
    return $escapedArray;
}
answered May 8, 2015 by rajesh

...