Quickly Validate Form Fields in PHP
When I have fields under a form
tag, I use isset()
function such as below:
if(isset($_POST) and isset($_POST['title']) and $_POST['date'])
{
//something;
}
and it gets bigger when I validate more fields. I am looking for any easy way of validate whether they are all filled or not in server-side with PHP.
Maybe something which navigates all the fields and check whether t开发者_JAVA技巧hey are filled as required.
<?php
$fields = array('field1', 'field2', 'field3', ...etc...); // Array of fields
$valid = true; //Assume all fields are correct and set this to false if not
foreach($fields as $field) {
if(!array_key_exits($field, $_POST)) {
$valid = false; // At least one key isn't set
break;
}
}
if($valid) {
// All fields are good
} else {
//Your user failed...
}
// required fields
$fields = array('title', 'date', 'email');
// optionally ignore blank posted values
$_POST = array_filter(array_map('trim', $_POST), 'strlen');
if (count(array_intersect_key($_POST, array_flip($fields))) == count($fields))
{
// all the required fields were posted
}
else
{
// ...not
}
$_POST
is an array, so you can fetch its element using foreach
and then test each element if it is empty or no, collecting errors if there and at the end send one error message.
I've found it amongst comment section on PHP Manual...
A little function which take an array as keys:
<?php
//note the s in the function name (keys)
function array_keys_exists($array,$keys) {
foreach($keys as $k) {
if(!isset($array[$k])) {
return false;
}
}
return true;
}
?>
//useful to validate a form for example
<form>
<input type="text" name="field1" /><br />
<input type="text" name="field2" /><br />
<input type="text" name="field3" /><br />
<input type="text" name="field4" /><br />
<input type="text" name="field5" /><br />
</form>
<?php
if(!array_keys_exists($_POST,
array("field1","field2","field3","field4","field5")
)) {
//some fields are missing, dont do anything (maybe hacking)
} else {
//code ...
}
?>
A more reusable solution would be to write a small function to verify a list of keys exist, such as
function array_keys_exist($keys, $search) {
// If we were passed a single key, use existing function
if (!is_array($keys)) {
return array_key_exists($keys, $search);
}
// If there are no keys in $search that are not in $keys
// We have all the keys
return 0 == count(array_diff($keys, array_keys($search)));
}
which could then be used for all your forms like this:
$requiredFields = array('title', 'date', 'details');
if (array_keys_exist($requiredFields, $_POST)) {
// Do your thing
}
Frankly, I'm not sure why this isn't already a built-in function
精彩评论