PHP我该如何使用它?

时间:2014-03-28 23:54:51

标签: php validation

我很确定这是什么以及如何在表单处理中使用它。它是否只删除不在$ expected []中的不需要的$ _POST条目?我还应该使用$ _POST ['carModel']来获取值吗?或者可能有更好的方法?

<?php
$expected = array( 'carModel', 'year', 'bodyStyle' );
foreach( $expected AS $key ) {
    if ( !empty( $_POST[ $key ] ) ) {
        ${$key} = $_POST[ $key ];
    }
    else 
    {
        ${$key} = NULL;
    }
}
?>

4 个答案:

答案 0 :(得分:1)

它使用相应POST字段的内容创建变量$ carModel,$ year等,如果没有任何内容则为null。

答案 1 :(得分:1)

<?php
// builds an array
$expected = array( 'carModel', 'year', 'bodyStyle' );
// loops over the array keys (carModel, year...)
foreach( $expected AS $key ) {
    // checks, if this key is found in the incomming POST array and not empty
    if ( !empty( $_POST[ $key ] ) ) {
        // assigns the value of POST, to a variable under the key name
        ${$key} = $_POST[ $key ];
    } else {
        // or nulls it, which is totally pointless :)  
        ${$key} = NULL;
    }
}
?>

$ expected数组的意图是为POST数组键提供白名单。 有更好的方法来实现它,尤其是filter_input(),filter_input_array()。

示例代码 http://www.php.net/manual/en/function.filter-input-array.php

答案 2 :(得分:0)

是的,伪代码$ {$ variable}是一个新变量的创建,又名:

//$_POST['test'],$_POST['future']
foreach( $_POST AS $key ) {
   ${$key} = $_POST[ $key ];
}

你将$ _POST [$ key]分配给$ test,比如$ test = $ _POST [$ key]; echo $ future; //具有相同的$ _POST ['future']

的值

现在你可以跳过使用$ _POST来使用$ test,post中的所有数组键应该分配在一个由键名调用的变量中;

在您的示例中,$ excepted工作就像过滤器一样,只分配此数组中的变量。在分配给$ {$}之前,您应该使用过滤器来清理$ _POST。

答案 3 :(得分:0)

如果在示例中发布数据

$_POST["carModel"] = "BMW";
$_POST["year"] = 2013;

这意味着......

$carModel = "BMW";
$year = 2013;
$bodyStyle = null;

相同
extract( $_POST );
相关问题