what is a good method to sanitize the whole $_POST array in php?

 ̄綄美尐妖づ 提交于 2019-11-28 17:13:53
johnny.rodgers

If the type of each of your input variables is a string and you want to sanitize them all at once, you can use:

// prevent XSS
$_GET   = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

This will sanitize your $_GET and $_POST arrays.

Seen here: PHP -Sanitize values of a array

Russell Dias

Depends what its being used for.

If you are inserting it into the database then mysql_real_escape_string() for quoted strings and type casting for numbers would be the way to go - well ideally prepared statements, but thats an entirely different matter.

If you plan on outputting the data onto the webpage then I would recommend something like htmlspecialchars()

If you plan on using the user input as a shell argument, then you would use escapeshellarg()

Moving onto your question about sending emails. Well, the following should suffice:

filter_var($_POST['message'], FILTER_SANITIZE_STRING);

All this does is basically strip tags and encode special characters.

There is no correct way to do blanket sanitation. What sanitation method you need depends on what is done to the data.

Sanitize the data directly before it is used.

This is what I use in all my projects:

function util_array_trim(array &$array, $filter = false)
{
    array_walk_recursive($array, function (&$value) use ($filter) {
        $value = trim($value);
        if ($filter) {
            $value = filter_var($value, FILTER_SANITIZE_STRING);
        }
    });

    return $array;
}

It allows to trim and sanitize a nested array of posted data

To apply specific filters on multiple fields, use a switch statement.

$post  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

foreach($post as $k => $v) {
    switch ($k) {
        case 'int_1':
        case 'int_2':
            $post[$k] = filter_var($v, FILTER_SANITIZE_NUMBER_INT) * 1;
            break;
        case 'float_1':
        case 'float_2':
            $post[$k] = filter_var($v, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION) * 1;
            break;
        default:
            break;
    }
}

Note: My IDE (NetBeans) warns about using global $_POST anywhere as a security violation, so I've just gotten into the habit of using a local $post variable instead. If you choose not to do the blanket string sanitation first, FILTER_SANITIZE_STRING could be used for the default: case.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!