This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
More concise way to check to see if an array contains only numbers (integers)
PHP checking if empty fields
I have form that submits 10 fields, and 7 of them should be filled, here is how i chek it now in PHP:
if (!$name || !$phone || !$email || !$mobile || !$email || !$state || !$street || ! $city) {
echo '<div class="empty_p">You have empty fields!!!</div>';}
else{
//process order or do something
}
My question is: is there more simple way to do this? Because sometimes I have even more strings to check (12-15)
Another possibility:
$elements = array($name, $email, $mobile);
$valid = true;
foreach ($elements as $element) {
if (empty($element)) {
$valid = false;
}
}
if ($valid) {
// complete
} else {
// alert! some element is empty
}
Something like this?
foreach($_POST as $key => $value)
{
if (empty($_POST[$key]))
{
echo '<div class="empty_p">'.$_POST[$key].' is empty.</div>';
}
}
It's good to be specific about where this data should be expected, e.g. $_POST:
if (!isset($_POST['name'], $_POST['phone'], $_POST['email'], $_POST['mobile'], $_POST['state'], $_POST['street'], $_POST['city'])) {
// something is up
}
You can shorten this code a little bit by creating an array with your required field names:
$required_fields = array('name', 'phone', 'email', 'mobile', 'state', 'street', 'city');
The 'check-for-existence' code can then be simplified to:
foreach ($required_fields as $f) {
if (!isset($_POST[$f])) {
// something is up
}
}
The better way ™
However, you should seriously consider combining both existence and validation / sanitization checks. PHP provides a family of filter functions functions that you can use to validate and/or sanitize your input variables. For example, to get equivalent behavior as above:
$required_fields = filter_input_array(INPUT_POST, array(
'name' => FILTER_UNSAFE_RAW,
'email' => FILTER_VALIDATE_EMAIL,
));
if (is_null($required_fields) || in_array(null, $required_fields, true)) {
// some fields are missing
}
Fields that exist but fail validation will be set to false, so this is how you detect such an event:
foreach ($required_fields as $name => $value) {
if (false === $value) {
// field $name failed validation (e.g. bad email format)
} elseif (!strlen(trim($value))) {
// field is empty
}
}
The best way would be to create some sort of form validator. However you can use this function:
<?php
function isAnyEmpty() {
$total = 0;
$args = func_get_args();
foreach($args as $arg)
{
if(empty($arg)) {
return true;
}
}
return false;
}
$var1 = 1;
$var2 = 'test';
$var3 = '';
if(isAnyEmpty($var1, $var2, $var3)) {
echo 'empty fields!';
}
?>
You could try creating a general validation class that could be reused and be more precise.
Some pseudo code:
<?
class validateFields {
$validators = array(
"name" => array(
"empty" => array(
"rule" => "some regex",
"errorMessage" => "name may not be empty"
),
"noNumbers" => array(
"rule" => "some regex",
"errorMessage" => "No numbers are allowed in the name field"
)
),
"otherVariable" => array(
"atLeast50chars" => array(
"rule" => "some regex",
"errorMessage" => "This field must be at least 50 chars"
)
)
);
public function Validate($post){
$errors = array();
foreach($_POST as $key => $value){
if(!array_key_exists($key, $validators)) {
continue;
}
foreach($validators[$key] as $validator) {
if(!preg_match($validator["rule"], $value) {
$errors[$key] = $validator["errorMessage"];
break;
}
}
}
return $errors;
}
}
?>
Then in your code you could do something like:
$errors = Validate($_POST);
foreach($error as $errorMessage) {
echo $errorMessage . "</br>";
}
Of course you could fancy this up, adding divs with classes right below/beside the concerning input field and load the $errorMessage into there.
I'm sure there's loads of examples out there :)
You can write Foreach loop
foreach($_POST as $key => $value)
{
if (!isset($_POST[$key]) || empty($_POST[$key])
{
echo '<div class="something">You have empty fields!!!</div>';
}
}
<input type="text" name="required[first_name]" />
<input type="text" name="required[last_name]" />
...
$required = $_POST['required'];
foreach ($required as $req) {
$req = trim($req);
if (empty($req))
echo 'gotcha!';
}
/* update */
OK! guys, easy...
You can make it more secure, just with type casting as all we programmers do for out coming data, like $id = (int) $_GET['id'], like $username = (string) addslashes($_POST['username']) and so on...;
$required = (array) $_POST['required'];
And then, what ever comes from post fields let them come, this code just seek what it need.
That is it! Uhh...
Related
Is there any simpler format for the following if statement below?
if((!empty($_SESSION['email'])) && (!empty($_SESSION['serial'])) && (!empty($_SESSION['name'])) && (!empty($_SESSION['number'])) && (!empty($_SESSION['institution'])) && (!empty($_SESSION['address'])) && (!empty($_SESSION['item2']))){
echo "OK u can proceed";
} else {
echo "U didn't complete the requested info";
}
Sorry if this is too simple for you, but really appreciate any pro suggestion.
Because conditional statement will "short circuit" on the first failure, re-writing your process using an iterator will be less performant.
If you only want to provide generalized feedback to the user, use your current method without the surplus parentheticals.
if(!empty($_SESSION['email']) &&
!empty($_SESSION['serial']) &&
!empty($_SESSION['name']) &&
!empty($_SESSION['number']) &&
!empty($_SESSION['institution']) &&
!empty($_SESSION['address']) &&
!empty($_SESSION['item2'])){
// valid
}
Alternatively (same same):
if(empty($_SESSION['email']) ||
empty($_SESSION['serial']) ||
empty($_SESSION['name']) ||
empty($_SESSION['number']) |
empty($_SESSION['institution']) ||
empty($_SESSION['address']) ||
empty($_SESSION['item2'])){
// invalid
}
Only if you wish to specify the cause of the invalidation should you bother to set up an iterative process. Furthermore, if you are going to perform iterations to validate, you can take the opportunity to remove any unwanted elements from the $_SESSION array that evil-doers may have injected to take advantage of any future loops on the superglobal.
$valid_keys=['email','serial','name','number','institution','address','item2'];
$validated=true; // default value
foreach($valid_keys as $key){
if(!empty($_SESSION[$key])){
$session_data[$key]=$_SESSION[$key];
}else{
echo "Oops, there was missing data on $key";
$validated=false;
break;
}
}
if($validated){...
// from this point, you can confidently run loops on `$session_data` or slap it directly into a pdo call knowing that it has been validated and ordered.
All that said, if there is even the slightest chance that your $_SESSION elements could hold zero-ish/false-y/empty values, then isset() is the better call (only NULL will get caught). Another good thing about isset() is that it allows multiple variables to be written into the single call and maintains the same/intended performance.
if(isset($_SESSION['email'],$_SESSION['serial'],$_SESSION['name'],$_SESSION['number'],$_SESSION['institution'],$_SESSION['address'],$_SESSION['item2'])){
// valid
}
or
if(!isset($_SESSION['email'],$_SESSION['serial'],$_SESSION['name'],$_SESSION['number'],$_SESSION['institution'],$_SESSION['address'],$_SESSION['item2'])){
// invalid
}
You could build a function where you pass all the keys you want to check.
I've changed $_SESSION to $SESSION to cheat the array with some values ...
<?php
$SESSION = [
'email' => 'xx',
'serial' => 'xx',
'name' => 'xx',
'number' => 'xx',
'institution' => 'xx',
'address' => 'xx',
'item2' => 'xx'
];
$keys = [
'email',
'serial',
'name',
'number',
'institution',
'address',
'item2'
];
if(isNotEmpty($SESSION, $keys)) {
echo "OK u can proceed";
} else {
echo "U didn't complete the requested info";
}
function isNotEmpty($array, $keys) {
foreach($keys as $key) {
if(empty($array[$key])) {
return false;
}
}
return true;
}
PHP Fiddle
Just "mind games"
$arr = array_flip('email', 'serial', 'name','number'...);
if (count(array_filter(array_intersect_key($_SESSION, $arr))) == count($arr)) {
This is just my opinion, but I think your expression is fine. Maybe you could format it in another way to make it more readable:
if ( !empty($_SESSION['email']) &&
!empty($_SESSION['serial']) &&
!empty($_SESSION['name']) &&
!empty($_SESSION['number']) &&
!empty($_SESSION['institution']) &&
!empty($_SESSION['address']) &&
!empty($_SESSION['item2']) ) {
/* Proceed */
} else {
/* Don't proceed */
}
Or maybe use a custom validation function:
/* My original version */
function filled_required_fields($fields, $array) {
$valid = true;
foreach ($fields as $field) {
$valid = $valid && !empty($array[$field]);
if (!$valid) return false;
}
return $valid;
}
/* Cleaner solution based on #caramba's answer */
function filled_required_fields($fields, $array) {
foreach ($fields as $field) {
if (empty($array[$field])) return false;
}
return true;
}
if (filled_required_fields(['email', 'serial', 'name', 'number', 'institution', 'address', 'item2'], $_SESSION) {
/* Proceed */
} else {
/* Don't proceed */
}
I have the following php code.
Im trying to find out the field name/key that does not exist without using hardcoded static text. Is there a php function that can do this. array_keys_exist is similar to what I want but it only allows for checking of a single key.
ex:
Something like
$keys_to_confirm = ['password','password_old',....];
$user_submitted_input_array = ['password'=>'...', 'somekey'=>'...' ];
bool : all_array_keys_exist($keys_to_confirm,$user_submitted_input_array);
Current code that uses static text to report the missing field/key name
if( isset($input['password']))
{
if( isset($input['password_old'])) )
{
if(isset($input['password_repeat'])) )
{
//good to go!
}
else
{
die('missing form element password_repeat.');
}
}
else
{
die('missing form element password_old.');
}
}
else
{
die('missing form element password.');
}
I had this code but it doesnt say what is missing.
//if the field doesnt exist for some reason lets create a dummy
if( ! isset($input['password'])
OR (!isset($input['password_repeat']))
OR (!isset($input['password_old'])) )
{
die('missing form element.');
}
Try:
foreach( array('password', 'password_repeat', 'password_old') as $key ) {
if( empty($input[ $key ]) ) {
echo 'Missing field: ' . $key;
}
}
You can probably come up with a one liner to do this using array_diff_key, but I think the above is concise enough.
Here's the one liner with array_key_diff. It's not the prettiest but functional.
$keys_to_confirm = array('password' => '','password_old' => '');
$user_submitted_input_array = array('password'=>'...', 'somekey'=>'...');
$validate = array_diff_key($keys_to_confirm, $user_submitted_input_array);
if( empty($validate) ) {
echo 'Passed';
} else {
echo 'Missing field: ' . key($validate);
}
My solution:
if ($field_miss = array_diff_key(array('password', 'password_old', '...'), array_keys($input))) {
echo 'Missing field: ', implode(', ', $field_miss);
}
everyone! I've been having a terrible time trying to figure out why my form validation doesn't recognize empty fields and return them as errors.
Here is a function I use to check the fields:
function check_required_fields($required_array) {
$field_errors = array();
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
$field_errors[] = $fieldname;
}
}
return $field_errors;
}
Then, my form is process like this:
if (isset($_POST['submit'])) { // Form has been submitted.
$errors = array();
// perform validations on the form data
$required_fields = array('client', 'banner', 'district', 'store', 'position', 'first_name', 'last_name', 'email', 'password');
$errors = array_merge($errors, check_required_fields($required_fields, $_POST));
and an IF statement checks for errors:
if ( empty($errors) ) {
$query =
The problem is, even if my fields are empty (and I checked them with var_dump($_POST)) PHP performs the $query. I think there is something wrong with the function. I hope someone can help me spot the error!
Here is the gist of my HTML code:
<form action="registration.php" method="post">
<label for="first_name" class="medium">First Name</label>
<input type="text" name="first_name" class="textbox short_field">
<button type="submit" name="submit" value="submit" class="form-submit-button">SUBMIT</button>
</form>
I also use the following functions to validate string length and it works just fine:
function check_max_field_lengths($field_length_array) {
$field_errors = array();
foreach($field_length_array as $fieldname => $maxlength ) {
if (strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength) { $field_errors[] = $fieldname;
}
}
return $field_errors;
}
and
$fields_with_lengths = array('first_name' => 30, 'last_name' => 30, 'email' => 50, 'password' => 30);
$errors = array_merge($errors, check_max_field_lengths($fields_with_lengths, $_POST));
"The problem is, even if my fields are empty (and I checked them with var_dump($_POST)) PHP performs the $query."
Your problem is caused by this condition: $var != 0. Php can cast variables of different types between each other, so empty string is equal to 0. Proof:
<?php
$var = '';
var_dump($var == 0);
Output: bool(true)
Now look at this sample, imitating, how php processes your condition:
<?php
$var = '';
var_dump(empty($var));
var_dump((empty($var) && $var != 0));
Output:
bool(true)
bool(false)
In the 2-nd case the boolean function returns false, therefore, the variable won't be added to the array of errors.
I don't know, what do you want to achieve with this: $var != 0. But the condition:
if (!isset($_POST[$fieldname]) ||
(empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
$field_errors[] = $fieldname;
}
can be easily switched to this:
if (empty($_POST[$fieldname])) {
$field_errors[] = $fieldname;
}
I'd like some help please, if its possible.
I have created two functions in order to display some messages when is set a $_GET after a redirect.Here's the code:
function display(){
if(isset($_GET['cnf_upd']) && $_GET['cnf_upd'] == '1'){
$value = "The update was successful!";
$type = "confirm";
construct_the_div($value, $type);
}
if(isset($_GET['err_upd']) && $_GET['err_upd'] == '1'){
$value = "The Update failed.";
$type = "error";
construct_the_div($value, $type);
}
if(isset($_GET['cnf_del']) && $_GET['cnf_del'] == '1'){
$value = "Deleted completely.";
$type = "confirm";
construct_the_div($value, $type);
}
if(isset($_GET['err_del']) && $_GET['err_del'] == '1'){
$value = "Unable to delete.";
$type = "error";
construct_the_div($value, $type);
}
}
function construct_the_div($value, $type){
// creating a div to display the message results
$div = "<div class=\"{$type}Msg\">\n";
$div .= "<p>{$value}</p>\n";
$div .= "</div><!-- end of {$type}Msg -->\n";
echo $div;
}
What I'd like to make is to try to improve the display function, as it gets longer and longer, so that there whould be only one (or two at most) if statement(s) if possible. So the value of the GET will be dynamicly inside the if condition and also if it has the preffix 'cnf_' it wil be a 'confirmMsg' and if it has the preffix 'err_' it wil be a 'errorMsg'.
Is it possible to make something like this???
function display() {
$messages = array(
'cnf_upd' => 'The update was successful!',
'cnf_err' => 'The Update failed.!',
// ...
// add all error and confirm there
// ...
);
foreach($_GET as $key => $value) {
if(strpos($key, 'cnf_')===0) {
$type = 'confirm';
$value = isset($messages[$key])
? $messages[$key]
: $key;
construct_the_div($value, $type);
}
if(strpos($key, 'err_')===0) {
$type = 'error';
$value = isset($messages[$key])
? $messages[$key]
: $key;
construct_the_div($value, $type);
}
}
}
The approach is not correct, it seems that only one message should occur at once (there cannot be "deleted completely" and "unable to delete" at once).
Try construct the parameters this way: ?msg=upd&msgType=cnf
function display(){
if (isset($_GET['msg']) && isset($_GET['msgType']))
{
$messages = array('cnf_upd'=>'The update was successful!',
'err_upd'=>'The update failed!',
'cnf_del'=>'The deletion was successful!',
'cnf_upd'=>'The deletion failed!',
);
if (isset($messages[$_GET['msgType'].'_'.$_GET['msg']))
construct_the_div($messages[$_GET['msgType'].'_'.$_GET['msg']], htmlspecialchars($_GET['msgType']));
}
there is still much to improve, but for start this is cleaner and safer.
I'm going to propose a different solution. Instead of setting different parameters in $_GET based on the message to be sent, set one parameter and parse its value.
// Start by setting integer constants:
define(CNF_UPD, 1);
define(ERR_UPD, 2);
define(CNF_DEL, 3);
define(ERR_DEL, 4);
Then when you set the value un $_GET, use the constant:
// Build the URL with a deletion error...
header("Location: http://example.com/script.php?msg=" . ERR_DEL);
Finally, use a switch to parse them
if (isset($_GET['msg'])) {
switch ($_GET['msg']) {
case CNF_UPD:
// Updated...
break;
case ERR_UPD:
// failed...
break;
// etc...
default:
// invalid code.
}
}
If you use a pattern of confirm/error/confirm/error for your integer constants, you can determine which it is by taking $_GET['msg'] % 2. Odd numbers are confirmations, evens are errors. There are of course many other ways you could lay this out, I just happen to have typed them in the alternating order you used. You could also do positive integers for confirmations and negatives for errors, for example.
$type = $_GET['msg'] % 2 == 1 ? $confirm : $error;
This is easily expanded to use multiple messages as well. Since they are integer values, you can safely construct a comma-separated list and explode() them when received.
$messages = implode(array(ERR_DEL,CNF_UPD));
header("Location: http://example.com/script.php?msg=$messages");
Unless you can somehow generate $value and $type based on the $_GET parameter (which I can't see how you would do), you could do something like:
$messages = array();
$messages[] = array('id' => 'cnf_upd', 'value' => 'The update was successful!', 'type' => 'Confirm');
$messages[] = array('id' => 'err_upd', 'value' => 'The Update failed.', 'type' => 'error');
...
foreach ($messages as $message) {
if(isset($_GET[$message['id']]) && $_GET[$message['id']] == '1'){
construct_the_div($message['value'], $message['type']);
}
}
When a user submit forms,i'm checking empty validation and data validation.
For ex:In data ,first field is name,i'll check whether user has entered any other characters else than alpha character's.if he has entered then will show him an error message.Name should contain minimum of 4 characters and max of 20 characters
I'm using this code but it is not working correctly.How to check the regex.
$validate = array("Category"=>"$productCategory", "Name" => "$productName");
$error = '';
foreach ($validate as $key => $field) {
if (preg_match('/^[a-z\d ]{4,20}$/i', $$field)) {
echo $error .= $field;
}
}
Thanks in advance!
You have a typo in the preg_match, you type $$field (2x$) instead of $field, your regex is fine it will match:
- a character between a - z (case insensitive)
or
- a digit between 0 - 9
or
- a "space" character.
Update code to answer #Andrius Naruševičius comment
$validate = array("Category" => $productCategory, "Name" => $productName);
$error = '';
foreach ($validate as $key => $field)
{
if (preg_match('/^[a-z\d ]{4,20}$/i',$field))
{
$error.= $field;
}
}
if($error)
{
echo $error;
exit;
}
Do you mean:
$validate = array("Category"=>$productCategory, "Name" => $productName);
foreach ($validate as $key => $field) {
if (preg_match('/^[\w\d]{4,20}$/i',$field)) {
echo $error .= $field;
}
}