Reputation: 1827
I'm just learning PHP and I'm following a tutorial. Now I'm on the part where we examine server-side form validation and the tutorial uses the request_import_variables
to get the values and validate them. But this method is deprecated now. How can I get the values from a form that are stored in an array? I tried using extract but I'm not that familiar with the syntax and I don't get the result that I want. Here is the code.
<?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" />
As a result I get You missed one or more fields
First Name
Last Name
Here is the section of the tutorial I'm stuck
Upvotes: 0
Views: 2544
Reputation: 617
Avoid extracting variables! Instead of this you should work with array directly. Discussion about this bad extract
practice is here.
As for your, code, you made a little mistake here:
extract($_POST['Form'], EXTR_PREFIX_ALL, "z");
This extract
will make variables from $_POST['Form']
array, such as $z_FName
, $z_LName
, $z_Age
, etc.
The code from tutorial:
import_request_variables("p", "z");
This import_request_variables
will make variables from $_POST
array, so it will be just $z_Form
.
So you need change
extract($_POST['Form'], EXTR_PREFIX_ALL, "z");
to
extract($_POST, EXTR_PREFIX_ALL, "z");
And change $zForm
to $z_Form
.
If you'll debug such cases, you may have a look to a get_defined_vars
function.
Upvotes: 2