如何使用extract()来获取表单的值?

时间:2015-09-01 13:51:25

标签: php forms validation

我只是在学习PHP,而且我正在学习一门教程。现在,我正在研究服务器端表单验证,本教程使用request_import_variables来获取值并验证它们。但是这个方法现在已经弃用了。如何从存储在数组中的表单中获取值?我尝试使用提取,但我不熟悉语法,我没有得到我想要的结果。这是代码。

<?php
//In this example I'm going to get the values of the form 
//and validate them on the server.
if(isset($_POST['Form'])) {
    //import_request_variables isn't supported anymore by php
    //import_request_variables("p", "z");
    extract($_POST['Form'], EXTR_PREFIX_ALL, "z");
    $missingFields = array();
    $required = array("FName"=>"First Name", "LName"=>"Last Name");

    while(list($var, $val) = each($required)){
        if(isset($zForm[$var]) && $zForm[$var] != ''){
            if(is_string($zForm[$var]))
                print "Everything ok <br />";
            else
                print "You have to provide a valid first and last name <br />";
        }
        else {
            $missingFields[$var] = $val;
        }
    }

    if(count($missingFields)){
        print "You missed out one or more fields:<br />";

        while(list($var, $val) = each($missingFields)){
            print $val . "<br />";
        }
    }
    else {
        print "Form passed!<br />";
        var_dump($zForm['Languages']);
        exit;
    }
}
?>

<form method="post" action="formValidation.php">
First Name: <input type="text" name="Form[FName]" /> (required)<br />
Last Name: <input type="text" name="Form[LName]" /> (required) <br />
Age: <input type="text" name="Form[Age]" /><br /><br />
Languages known:<br />
<input type="checkbox" name="Form[Languages][]" value="PHP" checked="checked"> PHP</input>
<input type="checkbox" name="Form[Languages][]" value="CPP"> C++</input>
<input type="checkbox" name="Form[Languages][]" value="Delphi"> Delphi</input>
<input type="checkbox" name="Form[Languages][]" value="Java"> Java</input>
<input type="submit" />

结果我得到You missed one or more fields First Name Last Name

Here is the section of the tutorial I'm stuck

1 个答案:

答案 0 :(得分:2)

避免提取变量!而不是直接使用数组。关于这种不良extract做法的讨论是here

至于你的代码,你在这里犯了一个小错误:

extract($_POST['Form'], EXTR_PREFIX_ALL, "z");

extract将从$_POST['Form']数组生成变量,例如$z_FName$z_LName$z_Age等。

教程中的代码:

import_request_variables("p", "z");

import_request_variables将从$_POST数组生成变量,因此它只是$z_Form

所以你需要改变

extract($_POST['Form'], EXTR_PREFIX_ALL, "z");

extract($_POST, EXTR_PREFIX_ALL, "z");

$zForm更改为$z_Form

如果您要调试此类情况,可以查看get_defined_vars函数。