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 != ;
}
Related
I'm trying to check whether a $_POST exists and if it does, print it inside another string, if not, don't print at all.
something like this:
$fromPerson = '+from%3A'.$_POST['fromPerson'];
function fromPerson() {
if !($_POST['fromPerson']) {
print ''
} else {
print $fromPerson
};
}
$newString = fromPerson();
Any help would be great!
if( isset($_POST['fromPerson']) )
{
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
Simple. You've two choices:
1. Check if there's ANY post data at all
//Note: This resolves as true even if all $_POST values are empty strings
if (!empty($_POST))
{
// handle post data
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
(OR)
2. Only check if a PARTICULAR Key is available in post data
if (isset($_POST['fromPerson']) )
{
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
Surprised it has not been mentioned
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['fromPerson'])){
Everyone is saying to use isset() - which will probably work for you.
However, it's important that you understand the difference between
$_POST['x'] = NULL; and $_POST['x'] = '';
isset($_POST['x']) will return false on the first example, but will return true on the second one even though if you tried to print either one, both would return a blank value.
If your $_POST is coming from a user-inputted field/form and is left blank, I BELIEVE (I am not 100% certain on this though) that the value will be "" but NOT NULL.
Even if that assumption is incorrect (someone please correct me if I'm wrong!) the above is still good to know for future use.
isset($_POST['fromPerson'])
The proper way of checking if array key exists is function array_key_exists()
The difference is that when you have $_POST['variable'] = null it means that key exists and was send but value was null
The other option is isset() which which will check if array key exists and if it was set
The last option is to use empty() which will check if array key exists if is set and if value is not considered empty.
Examples:
$arr = [
'a' => null,
'b' => '',
'c' => 1
];
array_key_exists('a', $arr); // true
isset($arr['a']); // false
empty($arr['a']); // true
array_key_exists('b', $arr); // true
isset($arr['b']); // true
empty($arr['b']); // true
array_key_exists('c', $arr); // true
isset($arr['c']); // true
empty($arr['c']); // false
Regarding your question
The proper way to check if value was send is to use array_key_exists() with check of request method
if ($_SERVER['REQUEST_METHOD'] == 'POST' && array_key_exists('fromPerson', $_POST)
{
// logic
}
But there are some cases depends on your logic where isset() and empty() can be good as well.
In that case using method isset is not appropriate.
According to PHP documentation: http://php.net/manual/en/function.array-key-exists.php
(see Example #2 array_key_exists() vs isset())
The method array_key_exists is intended for checking key presence in array.
So code in the question could be changed as follow:
function fromPerson() {
if (array_key_exists('fromPerson', $_POST) == FALSE) {
return '';
} else {
return '+from%3A'.$_POST['fromPerson'];
};
}
$newString = fromPerson();
Checking presence of array $_POST is not necessary because it is PHP environment global variable since version 4.1.0 (nowadays we does not meet older versions of PHP).
All the methods are actually discouraged, it's a warning in Netbeans 7.4 and it surely is a good practice not to access superglobal variables directly, use a filter instead
$fromPerson = filter_input(INPUT_POST, 'fromPerson', FILTER_DEFAULT);
if($fromPerson === NULL) { /*$fromPerson is not present*/ }
else{ /*present*/ }
var_dump($fromPerson);exit(0);
Try
if (isset($_POST['fromPerson']) && $_POST['fromPerson'] != "") {
echo "Cool";
}
I would like to add my answer even though this thread is years old and it ranked high in Google for me.
My best method is to try:
if(sizeof($_POST) !== 0){
// Code...
}
As $_POST is an array, if the script loads and no data is present in the $_POST variable it will have an array length of 0. This can be used in an IF statement.
You may also be wondering if this throws an "undefined index" error seeing as though we're checking if $_POST is set... In fact $_POST always exists, the "undefined index" error will only appear if you try to search for a $_POST array value that doesn't exist.
$_POST always exists in itself being either empty or has array values.
$_POST['value'] may not exist, thus throwing an "undefined index" error.
Try isset($_POST['fromPerson'])?
if (is_array($_POST) && array_key_exists('fromPerson', $_POST)) {
echo 'blah' . $_POST['fromPerson'];
}
if( isset($_POST['fromPerson']) ) is right.
You can use a function and return, better then directing echo.
I like to check if it isset and if it's empty in a ternary operator.
// POST variable check
$userID = (isset( $_POST['userID'] ) && !empty( $_POST['userID'] )) ? $_POST['userID'] : null;
$line = (isset( $_POST['line'] ) && !empty( $_POST['line'] )) ? $_POST['line'] : null;
$message = (isset( $_POST['message'] ) && !empty( $_POST['message'] )) ? $_POST['message'] : null;
$source = (isset( $_POST['source'] ) && !empty( $_POST['source'] )) ? $_POST['source'] : null;
$version = (isset( $_POST['version'] ) && !empty( $_POST['version'] )) ? $_POST['version'] : null;
$release = (isset( $_POST['release'] ) && !empty( $_POST['release'] )) ? $_POST['release'] : null;
I recently came up with this:
class ParameterFetcher
{
public function fetchDate(string $pDate):string{
$myVar = "";
try{
if(strlen($_POST[$pDate]) > 0){
$myVar = $_POST[$pDate];
}
}catch (Exception $faild){
die("field NULL or not set for $pDate");
}
[ ... other stuff ]
to fetch a date obviously, but it can take ANY post param. You can also check for GET this way.
I've got a problem with an input field in my php form. It looks like:
<input type="number" name="tmax" max="99" min="-99" placeholder="Temperatura max.">
I want to check whether the field is empty or not. But the problem is php considers 0 as empty.
if (empty($_POST['tmax'])) {
$tmax = null;
}else {
$tmax = $_POST['tmax'];
}
If the user leaves the input field empty the value is considered as 'null', which works perfectly. But if the user writes 0, which is a possibility in the form, it is also treated as empty.
I've also set the default as null in SQL but the problem is, if the input is empty, the program inserts 0 in the table.
SOLUTION:
This solution works fine for me:
if ($_POST['tmax'] == "") {
$tmax = null;
}else {
$tmax = $_POST['tmax'];
}
And also with is_numeric()
if (is_numeric($_POST['tmax'])) {
$tmax = $_POST['tmax'];
}else {
$tmax = 'null';
}
Check if the condition is empty, and also not zero. A zero-value is "empty", so by adding both checks, you ensure that the variable $tmax will be set to null if the input was empty and not zero.
if (empty($_POST['tmax']) && $_POST['tmax'] != 0) {
$tmax = null;
} else {
$tmax = $_POST['tmax'];
}
This will also accept "foo" as a value, so you should check or validate that the input is a valid number (and also in the ranges you specified). You can also implement is_numeric($_POST['tmax']), or even better, validate it with filter_var($_POST['tmax'], FILTER_VALIDATE_INT) to ensure that whatever was input is actually a number.
PHP.net on empty()
PHP.net on is_numeric()
PHP.net on filter_var()
PHP.net on flags for usage in filter_var()
As you state, 0 is considered empty.
The function you want is isset().
if (!isset($_POST['tmax'])) {
$tmax = null;
} else {
$tmax = $_POST['tmax'];
}
Alternatively, remove the not operator and switch the code blocks.
This code should work for what are you trying to get.
if (!isset($_POST['tmax']) || $_POST['tmax'] == '') {
$tmax = null;
}else {
$tmax = $_POST['tmax'];
}
You can use !is_numeric() instead empty()
thanks for such a important note, Rafa
if you want to have placeholder - you can use this code:
<input type="number" name="tmax" max="99" min="-99" onclick="if (this.value == '') {this.value='0';} " placeholder="Temperatura max.">
don't forget add validation (before send form check on empty fileds )
and php to:
$tmax = 0;
if (isset($_POST['tmax'])) {
$tmax = $_POST['tmax'];
}
you may use
if ($_POST['tmax'] == "") {
$tmax = null;
}else {
$tmax = $_POST['tmax'];
}
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='';
}
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
}
So basically, I have a function that is ran when a post is created on wordpress. I've modified this function by adding the following code.
$episodeID = $_POST['item_meta'][137];
$episodeVersion = $_POST['item_meta'][357];
if ($episodeVersion == "Subbed") {
$value = array("Subbed");
update_field('field_48', $value, $episodeID);
}
else if ($episodeVersion == "Dubbed") {
$value = array("Dubbed");
update_field('field_48', $value, $episodeID);
}
This code basically says, if the value of a field in that post is "Subbed" then update another checkbox field by checking the "Subbed" checkbox. If it's "Dubbed" then update the checkbox field by selecting the "Dubbed" checkbox.
This works perfectly fine, however there is no time when both of these checkboxes are checked. If I add a post with the Dubbed, it'll check dubbed, then if I add a post with Subbed, it'll uncheck dubbed and check subbed.
So basically, how can I make it so it doesn't actually uncheck whatever has already been checked. So what should I use to check to see if the checkbox is unchecked or checked? Some type of boolean true / false?
Okay, so I was able to manipulate some of the code and get it to work eventually.
All I had to do was check if the Subbed checkbox was already checked when executing the dubbed if statement, and vice versa.
Here is the updated code
$episodeID = $_POST['item_meta'][137];
$episodeVersion = $_POST['item_meta'][357];
if ($episodeVersion == "Subbed" && !(get_field('episode_sdversion') && in_array('Subbed', get_field('episode_sdversion', $episodeID))) ) {
if (get_field('episode_sdversion') && in_array( 'Dubbed', get_field('episode_sdversion'))) {
$value = array("Subbed", "Dubbed");
} else {
$value = array("Subbed");
}
update_field('field_48', $value, $episodeID);
}
if ($episodeVersion == "Dubbed" && !(get_field('episode_sdversion') && in_array('Dubbed', get_field('episode_sdversion', $episodeID))) ) {
if (get_field('episode_sdversion') && in_array( 'Subbed', get_field('episode_sdversion'))) {
$value = array("Subbed", "Dubbed");
} else {
$value = array("Dubbed");
}
update_field('field_48', $value, $episodeID);
}