0

我有这种 php 函数

function insertData($username,$name,$password) {
}

以及其他一些,例如:

function updateData($color, $hair,$eye) {
}

ETC..

因为这些参数可以包含一些引号或双引号,例如 " 或 '

有没有办法像

清理(​​所有函数参数)

无需编写 sanitize ($color); 消毒($头发);消毒($eye);

我正在寻找最通用的函数来清理(带斜杠)函数的所有参数

问候

4

3 回答 3

0

您可以使用func_get_args:和 foreach

function insertData($username,$name,$password) {
    $args = func_get_args();
    foreach ($args as $arg)
    {
        // sanitize and whatnot
    }
}
于 2013-04-25T08:15:16.050 回答
0

你的答案...

您不能只在函数外部调用函数来清理所有函数参数。您必须在函数中执行此操作,如下所示:

function foo(/* Polymorphic */){

    // Sanitize the arguments
    $arguments = sanitize(function_get_args());

    // Proceed with the rest of the function
    // $arguments will now be sanitized
}

function sanitize(/* Polymorphic */){

    // Get the functions arguments
    $arguments = function_get_args();

    // If the arguments exist then proceed to sanitizing
    if(is_array($arguments)){
        foreach($arguments as $key=>$value){
            $arguments[$key] = stripslashes($value);
        }
    }

    // Return the sanitized array
    return $arguments;
}

注意/* Polymorphic */评论;这实际上意味着您可以提交任意数量的参数。这里唯一的问题是你不知道哪些参数是哪些,除非你像这样提交它们:

// Call the foo function
foo(array(
    'username' => $username,
    'name'     => $name,
    'password' => $password
));

然后在 foo 函数中,您将能够像这样访问参数:

function foo(/* Polymorphic */){

    // Sanitize the arguments
    $arguments = sanitize(function_get_args());

    // You only want the first item in the arguments array so remove the others...
    $arguments = $arguments[0];

    // Proceed with the rest of the function
    echo 'Username: '.$arguments['username']."\n";
    echo 'Name: '.$arguments['name']."\n";
    echo 'Password: '.$arguments['password'];

}

然而...

如果您出于 MySQL(或任何其他数据库)的目的剥离斜线,那么我强烈建议您查看 MySQLi 或 PDO 库和准备好的语句。如果您使用准备好的语句,则无需进行剥离斜杠的工作。有关更多信息,请参阅以下链接:

http://php.net/manual/en/pdo.prepared-statements.php

于 2013-04-25T08:16:15.790 回答
0
function stripslashes_deep($value)
{
    $value = is_array($value) ?
                array_map('stripslashes_deep', $value) :
                stripslashes($value);

    return $value;
}


$array = func_get_args();
$array = stripslashes_deep($array);

print_r($array);
于 2013-04-25T08:16:20.337 回答