Php Error with IF statements & validation - php

I am trying to validate an input using a form, through the use of an if statement.
if (isset($_POST['weekly-rate']))
{
$weekly_rate = $_POST['weekly-rate'];
if(!isset($_POST['weekly-rate']))
{
$error_messages[]= 'Weekly rate was not set';
}
else
{
$weekly_rateOK = true;
}
}
else
{
$error_messages[] = 'Weekly rate was not set...';
}
When I run this it gives doesn't give me the output I want, which is Weekly rent was not set. Am I incorrect in thinking that
if(!isset($_POST['weekly-rate']))
{
$error_messages[]= 'Weekly rate was not set';`
Means, if an input is not set, run the error message, weekly rate was not set.
However all I receive is nothing

Your understanding of isset() is correct. However, the form always posts the field back to your backend code which triggers isset() to be true all the time. You may look at using empty() instead.
A simplified version would look like this
$weekly_rateOK = !empty($_POST['weekly-rate']);
if (!$weekly_rateOK) {
$error_messages[] = 'Weekly rate was not set...';
}
You may need to add an integer check if needed.

If you are using a text input/select with a name, then the input/select is always posted and is set, but with an empty string. If it is a checkbox or radio buttons, then they will be set only if the checkbox is checked or a radio button is selected.
I have written a sample validation function, inspired by Laravel. You can check it here, and extend it by adding additional cases:
function validate ($rule_bag, $input) {
$flag = true;
$error_bag = [];
foreach ($rule_bag as $item => $rules){
$rules = is_array($rules) ? $rules : array_filter(explode(',', $rules));
foreach($rules as $rule){
$rule = trim($rule);
switch(mb_strtolower(trim($rule))){
case 'required': {
// checking isset then empty to be compatible with php <= 5.4
if (!isset($input[$item]) || empty($input[$item]))
{
$flag = false;
!isset($error_bag[$item])?$error_bag[$item]=[]:null;
$error_bag[$item][] = $rule;
}
break;
}
default: {
if (isset($input[$item])){
try {
if (!preg_match($rule, $input[$item])){
$flag = false;
!isset($error_bag[$item])?$error_bag[$item]=[]:null;
!isset($error_bag[$item]['regex'])?$error_bag[$item]['regex']=[]:null;
$error_bag[$item]['regex'][] = $rule;
}
}
catch(Exception $e){
echo $e->getMessage();
}
}
}
}
}
}
return $flag ? $flag : $error_bag;
}

Related

How to handle empty post (upto 20 post) without using empty() and "&&" operator

I am receiving post values. I want a suggestion for logic to handle empty or not set post values.
Is there such a way if one of them receives empty post, the $Data array should not receive anymore values and make it empty. In other words, i am trying to immitate the try and catch feature. If on any POST is empty, ignore reading the rest of POST and make that array as empty
Is my second draft considred valid?
First draft
if(!empty(isset($_POST["SHOWSCHEDULE_SHOWTYPE"]))){
$DATA["SHOWSCHEDULE_SHOWTYPE"] = $_POST["SHOWSCHEDULE_SHOWTYPE"];
}
if(!empty(isset($_POST["SHOWSCHEDULE_SHOWTITLE"]))){
$DATA["SHOWSCHEDULE_SHOWTITLE"] = $_POST["SHOWSCHEDULE_SHOWTITLE"];
}
if(empty($DATA)){
//do something
}else{
//do something else
}
Second draft
try{
if(!empty(isset($_POST["SHOWSCHEDULE_SHOWTITLE"]))){
$DATA["SHOWTITLE"] = $_POST["SHOWSCHEDULE_SHOWTITLE"];
}else{
throw new Exception('POST SHOWSCHEDULE_SHOWTITLE');
}
if(!empty(isset($_POST["SHOWSCHEDULE_SHOWTYPE"]))){
$DATA["SHOWTYPE"] = $_POST["SHOWSCHEDULE_SHOWTYPE"];
}else{
throw new Exception('POST SHOWSCHEDULE_SHOWTYPE');
}
} catch (Exception $e) {
echo 'ERROR: ', $e->getMessage(), "\n";
unset($DATA);
}
You can use one if statement with all required POST parameters.
if(!empty($_POST['var1']) && !empty($_POST['var2']) && !empty($_POST['var3']) && !empty($_POST['var4'])):
/*and then assign all the POST values to a $DATA array as you want.*/
$DATA['var1'] = $_POST['var1'];
$DATA['var2'] = $_POST['var2'];/* and so on..*/
endif;
I personally prefer to white list values that I loop through and assign.
<?php
$valid_keys = ['SHOWSCHEDULE_SHOWTYPE', 'SHOWSCHEDULE_SHOWTITLE'];
$at_least_one_empty = false;
foreach($valid_keys as $data_key)
{
$data[$data_key] = isset($_POST[$data_key])
? trim($_POST[$data_key]) // Remove accidental user whitespace.
: ''; // If unsubmitted - set to empty string.
if($data[$data_key] === '')
$at_least_one_empty = true;
}
if($at_least_one_empty) {
unset($data);
} else {
process($data);
}
Note with the sample code above an unsubmitted value will be assigned the empty string. This might not be the behaviour you want.
However if you just want to assign and check you received all inputs this might do (no filtering or validation):
<?php
$valid_keys = ['SHOWSCHEDULE_SHOWTYPE', 'SHOWSCHEDULE_SHOWTITLE'];
foreach($valid_keys as $data_key)
$data[$data_key] = $_POST[$data_key] ?? null;
$not_all_received = in_array(null, $data, true);

PHP check empty post data in array

HTML markup
<input name="one[name]">
<input name="one[email]">
<input name="two[message]">
...
alot input
..
I pass that two array data from jquery to php, i need check if the field is empty by php and exit when find one of them is empty.
But i dont want do it one by one, can it done by php function like foreach or other?
This is what i tried but fail.
$data_one = $_POST['one'];
$data_two = $_POST['two'];
if (empty( $_POST['one'] )) { // i only need check `$data_one` in this example
exit('some field are empty');
} else {
echo('field are filled');
// continue other function
}
Above code keep return field are filled message, whether i fill the input field or not.
Thanks so much.
$allFilled = true;
foreach($_POST['one'] as $key=>$value){
if(empty($value)){
$allFilled = false;
exit('some fields are empty');
}
}
if($allFilled){
exit('all fields are filled');
}
Making use of array_filter and count functions
<?php
$data_one = $_POST['one'];
$data_one_filter = array_filter($_POST['one']); //Remove indexes of null or 0 - certainly name and email can't be 0
$data_one_count = count($_POST['one']); //count actual number of POST variables
$data_two = $_POST['two'];
if (count($data_one_filter) === $data_one_count) {
exit('fields are filled');
} else {
echo('some fields are empty');
// continue other function
}
You are sending data as array. So you seed to check this data as array like this:
$data_one = $_POST['one']['name'];
$data_two = $_POST['two']['message'];
if (empty( $_POST['one']['name'] )) { // i only need check `$data_one` in this example
exit('some field are empty');
} else {
echo('field are filled');
// continue other function
}
Try this
foreach($_POST['one'] as $key=>$value){
if(empty($value)){
exit('some field are empty');
}
}
echo "All fields are filled";

If any field in array is not empty, display message - PHP / [POST] form

I have a form with 25+ fields. I want to display a message if ANY of the fields in the array are NOT empty.
$customfields = array('q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'q7', 'q8', 'q9', 'q10', 'q11', 'q12', 'q13', 'q14', 'q15', 'q16', 'q17', 'q18', 'q19', 'q20', 'q21', 'q22', 'q23', 'q24');
I've taken a look at similar SO questions for verifying that all fields are not empty, i.e.:
$error = false;
foreach($customfields as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
echo "Here's an awesome message!";
} else {
echo "None for you, Glen Coco.";
}
How do I do the opposite - display a message if ANY one or more than one fields in the array are not empty?
Thanks in advance!
I think you want to take a look into the NOT operator.
You can just write this:
if (!empty($_POST[$field])) {
//^ See here the NOT operator
$error = true;
}
For more information see the manual: http://php.net/manual/en/language.operators.logical.php
Do the opposite comparison in the if:
$error = false;
foreach($customfields as $field) {
if (!empty($_POST[$field])) {
$error = true;
break; // get out of foreach loop
}
}

PHP improve my show message function

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']);
}
}

Check if atleast one field is not empty in PHP

I have these fields: weight, size_1, size_2, size_3
How can I check so minimum one of these fields are filled.
If its under the minimum then it should output "Error, fill one atleast"
I can do this with long if statements, that checks for empty, but is their a better way?
The fields come from an form submission, so it looks like this to get them:
$_POST['weight'];
$_POST['size_1'];
$_POST['size_2'];
$_POST['size_3'];
Assuming they are all in an array:
function check_for_input($array){
foreach($array as $value){
if($value != "") return true;
}
return false;
}
Use it like so:
if(check_for_input($_POST)){ /*...*/ }
else { die("Error, fill one at least"); }
Update with filter:
Assuming they are all in an array:
function check_for_input($array, $filter){
foreach($array as $key=>$value){
if($value != "" && in_array($key, $filter)){
return true;
}
}
return false;
}
Use it like so:
$filter = array('weight', 'size_1', 'size_2', 'size_3', /*...*/);
if(check_for_input($_POST, $filter)){ /*...*/ }
else { die("Error, fill one at least"); }

Categories