Checking for unfilled fields with PHP - php

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
}

Related

transfer value to another page PHP

if(isset($_POST['submit']) and $_POST['searcheditem'] != "") {
$value = $_POST['searcheditem'];
header("Location : anotherpage.php");
}
I use this code in my project, but when I am redirected to anotherpage.php I can't use $value. It is not equal to $_POST['searcheditem'] at that page.
What can I do?
You have 2 options in this case:
1. Use a query string
$value = $_POST['searcheditem'];
header("Location : anotherpage.php?myValue=".$value);
// then inside anotherpage.php
echo $_GET['myValue']; // make sure to sanitize this data
2. Use Sessions
$value = $_POST['searcheditem'];
$_SESSION['myValue'] = $value; // make sure to use session_start() at the top of the page
header("Location : anotherpage.php");
// then on the anotherpage.php page
// make sure you call session_start() at the top of this page too
echo $_SESSION['myValue']; // make sure to sanitize this too
You can do it in two ways, either can set it in session or can pass like query string
Query string method:
if(isset($_POST['submit']) and $_POST['searcheditem'] != "") {
$value = $_POST['searcheditem'];
header("Location : anotherpage.php?value=$value ");
}
Session Method:
if(isset($_POST['submit']) and $_POST['searcheditem'] != "") {
$value = $_POST['searcheditem'];
session_register("value"); // USE THIS ONLY IF YOUR PHP VERSION IS < 5.3.0
$_SESSION["value"] = $value;
header("Location : anotherpage.php");
}

php is not detecting all empty fields

I've got the following line of code in PHP at the top of the page making sure all form fields have content in them and not submitted empty...
if(!isset($_POST['name'])) { $err_name = 1; }
if (!isset($_POST['phone'])) { $err_phone = 1; }
if (!isset($_POST['email'])) { $err_email = 1; }
if ((!isset($_POST['serve'])) && ($_POST['other'] == "")) { $err_serve = 1; }
name is a text input
email is a text input
phone is a text input
serve is a checkbox array
other is a text input
Then below that I've got the following lines which allow the php code to continue if there are no errors (above)
if (($err_name != 1) && ($err_phone != 1) && ($err_email != 1) && ($err_serve != 1)) {
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$phone = $_POST['phone']; // required
$serve = $_POST['serve'];
$other = $_POST['other'];
Then I've got this next to each form field...
<?php if ($err_name == 1) { echo '<font color="red">Name cannot be empty</font>'; } ?>
<?php if ($err_phone == 1) { echo '<br /><font color="red">Phone cannot be empty</font>'; } ?>
<?php if ($err_email == 1) { echo '<font color="red">Email cannot be empty</font>'; } ?>
<?php if($err_serve == 1) { echo '<br /><font color="red">You must choose at least 1 area to serve</font>'; } ?>
Can someone please help me figure out WHY its doing the following...
if I take && ($err_serve != 1) out of the 2nd code, everything
except phone shows error messages
if I leave it in, ONLY err_serve throws error. The others are
ignored and no error is displayed.
Phone refuses to throw error messages. This is everything where $_POST
handling is in the php.
Note that all tests are done by submitting a completely empty form
The values will be set whether or not they are filled with a value. If it's an empty value, it's still a value.
Instead of using isset(), use empty(). It checks both if:
The value exists at all
The value is something other than 0, an empty string, false, etc.
The reason it works for the checkbox, is because when a checkbox is not checked, the browser does not send the value at all. This is contrary to text fields. A browser will send the value of a text field whether or not it's empty.
http://ca2.php.net/manual/en/function.empty.php

Shorting isset POST? [duplicate]

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='';
}

php ! operator not working

I have this code for a few check-boxes, works fine like this
foreach($_POST as $key => $order_type) {
if ('1' == $_POST[$key]) $_POST[$key] = '0';
}
if I negate the if it stops working and I'm sure that some are not == '1'; it just sets them to NULL.
foreach($_POST as $key => $order_type) {
if ('1' != $_POST[$key]) $_POST[$key] = '0';
}
do I miss anything ? tried with !('1' == $_POST[$key]) too.
Thanks
Checkboxes only get sent to the server if they are checked.
I assume that they have a value of 1, so you will be able to find these in the $_POST array. However, there will be none where the value is 0 (unless you specify a value of 0 in the html and check the box...).
To check checkboxes, you need to use isset as the value is really not that important, it is either set (checked) or not and then it simply does not appear.
How about a simple if/else?
if ('1' == $_POST[$key]) {
$_POST[$key] = '0'; }
else {
Do this if it's != ;
}

php captcha code not working

I'm using an old random() function for creating a validation code for an AJAX commenting system I found on the web (source code at LINK ).
The idea behind is pretty simple:
function Random()
{
$chars = "ABCDEFGHJKLMNPQRSTUVWZYZ23456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i <= 4)
{
$num = rand() % 32;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
$random_code = Random();
and then in the form, just before the SUBMIT button:
<label for="security_code">Enter this captcha code: <b><? echo $random_code; ?></b></label>
<input type="text" name="security_code" id="security_code" />
<input name="randomness" type="hidden" id="randomness" value="<?php $random_code; ?>">
My AJAX commenting system uses something like this for checking if a field is blank (ie. if there are any errors):
$errors = array();
$data= array();
[...]
if(!($data['name'] = filter_input(INPUT_POST,'name',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
{
$errors['name'] = 'Please enter a name.';
}
if(!empty($errors)){
[...]
}
so I wrote this:
if(!($data['security_code'] = filter_input(INPUT_POST,'security_code',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
{
$errors['security_code'] = 'You did not enter the validation code.';
}
elseif(!($data['security_code'] = $randomness))
{
$errors['security_code'] = 'You entered the validation code incorrectly. Please note that it is case sensitive.';
}
However when I click on the SUBMIT button after having inserted a random text in the validation code textfield ( test it by yourself at LINK ) I always get the "You entered the validation code incorrectly." message.
print_r($_POST) gives an empty array and then the script hangs after I click on submit:
Array
(
)
What am I missing? The original captcha code gets lost at some point in the validation process (the 3rd and 4th blocks of code).
Thanks in advance
After seeing your code here, I see that the static function validate doesn't know the variable $randomness! From your submit.php, you are making the following call:
$arr = array();
$validates = Comment::validate($arr);
The function validate doesn't know anything about the variable $randomness unless you pass such a thing to it - it is in a different scope.
Try modifying the above mentioned code as such:
$arr = array(); // no change here
$randomness = isset($_POST['randomness']) ? $_POST['randomness'] : '';
// Check for empty randomness before you validate it in Comment::validate
// so that you donot verify for '' == '' there.
$validates = Comment::validate($arr, $randomness);
And alter the validate function as follows:
public static function validate(&$arr, $randomness)
{
I know its not the elegant solution - that would require few more things that you'd learn well for yourself, this is just to show you the way...
Let me know how it goes.
instead of:
<input name="randomness" type="hidden" id="randomness" value="<?php $random_code; ?>">
write:
<input name="randomness" type="hidden" id="randomness" value="<?php echo $random_code; ?>">
also instead of:
elseif(!($data['security_code'] = $randomness))
{
$errors['security_code'] = 'You entered the validation code incorrectly. Please note that it is case sensitive.';
}
maybe this:
elseif($data['security_code'] != $randomness) {
$errors['security_code'] = 'You entered the validation code incorrectly. Please note that it is case sensitive.';
}
also, from where $data get its values? $_POST, $_GET?
print_r() it and also the $_REQUEST to light up.

Categories