This question already has answers here:
How do I add on multiple $_POST['row'] and variables? [closed]
(2 answers)
Closed 9 years ago.
I have many isset checkings:
if (isset($_POST['name']) && isset($_POST['day']) && isset($_POST['month']) && isset($_POST['year']) && isset($_POST['email']) && isset($_POST['email2'])&& isset($_POST['pass']) && isset($_POST['pass2']))
{
Is there a way to short it?
$isset = array
(
'name', 'day', 'month', 'year',
'email', 'email2', 'pass', 'pass2'
);
foreach ($isset As $set)
{
if (!isset($_POST[$set]) || empty($_POST[$set]))
{
echo 'error';
break;
}
}
Is that correct?
You could use a loop and empty only:
$keys = array('name', 'day', 'month'); // ...
foreach ($keys as $key) {
if (empty($_POST[$key])) {
// fail
break;
}
}
Or you could use array_diff_key():
if (array_diff_key(array_flip($keys), $_POST)) {
// fail (some keys not present in $_POST)
}
isset() can take multiple arguments, so you can shorten it simply like this.
if (isset($_POST['name'], $_POST['day'], $_POST['month'], $_POST['year'], $_POST['email'], $_POST['email2'], $_POST['pass'], $_POST['pass2']))
PHP Docs: http://php.net/manual/en/function.isset.php
Define a function like this:
function getPost($key, $default = null) {
if (isset($_POST[$key])) {
return $_POST[$key];
}
return $default;
}
Then you can skip the isset verification. If there's no sucho value, by default, the function will return null.
If you are sending these from an input form and your default value attribute is value="" then it will still be set in $_POST.
For example, if the previous page has:
<input type="text/css" id="email" name="email" value="" />
Then if the user leaves it blank, isset($_POST['email']) will return true, and $_POST['email'] will have a value of "". That's useless, right?
Try this.
$c = 0;
foreach($_POST as $key => $value)
{
$value = trim($value);//Makes sure there's no leading, or ending spaces. Safe to guard against a string that is " " instead of "".
if(strlen($value) > 0)
{
$c++;
}
else
{
echo "$_POST['" . $key . "'] has a problem.";
}
break;
}
Then your new if statement for whatever conditions you had in mind could be:
if($c == 8)//8 being the number of keys you're expecting to not be "" or null.
{
//Your conditions.
}
This is good to keep in mind. You are only testing 8 array keys, but what if you had 800? Something like this would be a necessity.
Depends on what you are doing, if it is to set a value, the ternary operator works wonders:
isset($_POST['day'])?$day=_POST['day'] :$day='';
after that line, $day is always set and you only test with if($day).
If there are many values, you can always run this assignment in a loop:
foreach(array('day','month','name') as $var)
{
isset($_POST[$var])?$$var=$_POST['$var']:$$var='';
}
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 am creating a checkout page that requires the client to fill out his personal information as well as his credit card details (this part using stripe).
I was wondering, what is the best way to check whether the fields are filled up or not? Shall I do it in the processingPayment.php that $_POSTs the fields and processes payment, and in case the fields were not filled, I would redirect back to checkout?
Or is it a better idea to use js to check on the spot before submitting the form?
if in the processing page, I would try something like this:
if (empty($firsName) || empty($lastName) || empty($address) || empty ($city) || empty ($state) || empty($zip))
{
header('Location: checkout.php');
}
But I would need to re-send the values that were entered so the checkout page receives them and the user doesn't have to re-fill every field again...
Something like this?
foreach($_POST as $key=>$val) {
if( empty($val) ) {
echo "$key is empty";
}
}
The best method with PHP is to have an array of possible arguments:
$array = array('firstName', 'lastName');
foreach($array as $val) {
if( empty($_POST[$val]) ) {
echo "$val is empty";
}
}
Otherwise, client side validation works too, but can always be disabled. To be completely safe, use both client and server side.
You can use the session to store the entered data, but you would need to check each value separately:
PHP
<?php
session_start();
foreach ($_POST as $key => $value) {
if (strlen(trim($value)) <= 0) { //You could replace '0'
$_SESSION[$key] = $value;
}
}
?>
FORM
<form>
First name: <input type="text" value="<?php $_SESSION['firstName'] ? $_SESSION['firstName'] : ''; ?>" placeholder="First Name" />
....
</form>
The $_SESSION['firstName'] ? $_SESSION['firstName'] : ''; is the same as
if ($_SESSION['firstName']) return $_SESSION['firstName']
else return '';
it is more readable in the HTML(View) that the full if statement
$var = isset($_POST['field']) ? $_POST['field'] : '';
$var2 = isset($_POST['field2']) ? $_POST['field2'] : '';
// and so on
if( empty($var) || empty($var2) )
{
//it's empty
}
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']);
}
}
I'm currently writing up a function in order to validate a URL by exploding it into different parts and matching those parts with strings I've defined. This is the function I'm using so far:
function validTnet($tnet_url) {
$tnet_2 = "defined2";
$tnet_3 = "defined3";
$tnet_5 = "defined5";
$tnet_7 = "";
if($exp_url[2] == $tnet_2) {
#show true, proceed to next validation
if($exp_url[3] == $tnet_3) {
#true, and next
if($exp_url[5] == $tnet_5) {
#true, and last
if($exp_url[7] == $tnet_7) {
#true, valid
}
}
}
} else {
echo "failed on tnet_2";
}
}
For some reason I'm unable to think of the way to code (or search for the proper term) of how to break out of the if statements that are nested.
What I would like to do check each part of the URL, starting with $tnet_2, and if it fails one of the checks ($tnet_2, $tnet_3, $tnet_5 or $tnet_7), output that it fails, and break out of the if statement. Is there an easy way to accomplish this using some of the code I have already?
Combine all the if conditions
if(
$exp_url[2] == $tnet_2 &&
$exp_url[3] == $tnet_3 &&
$exp_url[5] == $tnet_5 &&
$exp_url[7] == $tnet_7
) {
//true, valid
} else {
echo "failed on tnet_2";
}
$is_valid = true;
foreach (array(2, 3, 5, 7) as $i) {
if ($exp_url[$i] !== ${'tnet_'.$i}) {
$is_valid = false;
break;
}
}
You could do $tnet[$i] if you define those values in an array:
$tnet = array(
2 => "defined2",
3 => "defined3",
5 => "defined5",
7 => ""
);
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...