3

$_REQUEST[]在一个 php 文件中, or接收到很多变量$_POST[],我必须检查它们,以防它的值null与 function isset(),这很麻烦。有更好的解决方案吗?

4

4 回答 4

4

如何使用 and 的组合in_arrayarray_map例如:

// array of possible parameters that can be passed by the client
$keys = array('username','password');

// this will store the names of the ones that are not present
$missing = array();

foreach($keys as $key) {
    if(!in_array($key, $_POST)) {
        $missing[] = $key;
    }
}

$nullOffsets = array_map("is_null", $_POST);

echo 'Printing missing params:<br />';
print_r($missing);
echo 'Printing null existing params:<br />';
print_r($nullOffsets);
于 2009-11-16T10:35:47.330 回答
0

如果您在数组中有变量(不要只使用请求或发布数组),您可以循环调用isset()函数。根据您当前的代码,这可能会“更好”。

于 2009-11-16T10:36:28.923 回答
0

用户输入检查很麻烦,但它是必要的邪恶。

就个人而言,我更喜欢不使用$_GET$_POST将所需内容复制到我自己的变量中进行处理。

在我的 .php 文件的顶部,我保留了一个数组,其中包含我希望从中复制的值的名称$_GET$_POST

这加起来是:

// the following array needs to be modified when you change your input specs
$inputAllowed = array("name", "title", "company");
$input = array();
foreach($inputAllowed as $key)
    if( array_key_exists( $key, $_POST ) )
        $input[$key] = $_POST[$key];
    else
        $input[$key] = "";

很容易在其中添加一个“is_null”检查,以防万一某些东西不应该为空。或者你可以先让循环结束,然后循环 $input

于 2009-11-16T10:49:40.127 回答
0

您可以尝试将数组包装在一个对象中。

class ArrayWrapper {
    private $data;
    public function __get($var) {
    if (!isset($this->data[$var])) {
        return false;
    }
    else {
        return $this->data[$var];
    }
    }
    public function __construct($a) {
    $this->data = $a;
    }
}

$a = array('test' => 1);

$aw = new ArrayWrapper($a);

if ($aw->test != false) {
    echo "test: ".$aw->test;
}
if ($aw->foo != false) {
    echo "foo: ".$aw->foo;
}
于 2009-11-16T11:01:47.513 回答