Check if form element sent but empty with PHP - php

I'd like to separate two things.
If a $_POST["something"] was sent, BUT empty.
OR
If a $_POST["something"] was not sent.
Is there a way?

You might be tempted to use empty(), but it blows up in your face if your possible values include a 0. Best to use something like:
if (isset($_POST['something'])) {
// the form field was sent ...
if ($_POST['something'] === '') {
// the form field was sent, but is empty
}
}
This works, as ALL data coming out of the _GET/_POST/_REQUEST superglobals is a string, regardless of whether it's a number or not.

You'll want to use isset()
if (isset($_POST["something"])){
echo "The Post Variable 'something' was posted";
if (strlen($_POST["something"])==0)
echo "The Post Variable is blank";
else
echo "The Post Variable Contains ".$_POST['something'];
}

look towards isset and empty.
http://php.net/manual/fr/function.isset.php
http://php.net/manual/fr/function.empty.php
Edit : The comments below are true. Empty should be used for empty strings, not numeric values, float values or a zero in a string​​. However, here's a function if you need to accept these as valid values:
function is_blank($value) {
return empty($value) && !is_numeric($value);
}

i use the php function isset() to check if a POST was sent or not
http://php.net/manual/en/function.isset.php

if ($_POST["something"])
will return true if there is such field
if $_POST["something"] == ""
will do the rest

Related

Correct Way to determine if function is set

i cant seem to find a solution to my issue. im trying to check if the value of a function has been set and if it has do some stuff however when i run the below codes the bottom one throws a error the code at the bottom is the code i wish to use
seems pointless calling the function into a variable just to see if its set
//working check if set
$wa_passwordreset = WA_FN_Validate_Post($_POST['wa_passwordreset']);
if(isset($wa_passwordreset))
{
echo"do some stuff";
}
//NOT working check if set
if(isset( WA_FN_Validate_Post($_POST['wa_passwordreset']) ))
{
echo"do some other stuff";
}
As per PHP manual:
isset — Determine if a variable is set and is not NULL
isset actually test if a variable is set, not if a function returns any value. That is why your code doesn't work.
im trying to check if the value of a function has been set
Functions do not have values. Functions may return values. You can't check if a function has a value and if it's set.
Moreover,
$wa_passwordreset = WA_FN_Validate_Post($_POST['wa_passwordreset']);
if(isset($wa_passwordreset))
{
echo "do some stuff";
}
this portion of code will always return true. The reason for that is that even if WA_FN_Validate_Post would return an empty string, the variable $wa_passwordreset will be considered set and isset check will always return true. To avoid this, you should either check your $_POST like this:
if(isset($_POST['wa_passwordreset']))
{
$wa_passwordreset = WA_FN_Validate_Post($_POST['wa_passwordreset']);
echo "do some stuff";
}
Or if it's vital for you to maintain the order and check after WA_FN_Validate_Post, use empty:
$wa_passwordreset = WA_FN_Validate_Post($_POST['wa_passwordreset']);
if(isset($wa_passwordreset) && !empty($wa_passwordreset)) // be extra paranoid!
{
echo "do some stuff";
}

PHP - proper check if $_POST['variable'] is posted

I want to check if $_POST['submit'] is posted.
My original code was:
if ($_POST['submit']) { }
But I have a PHP notice with this code - "Undefined index: submit in..."
So to remove the notice I have to write this:
if (isset($_POST['submit'])) { }
But this is pointless because $_POST array is global and it return always true.
Also if I want to check if $_POST['submit'] is not 0 without PHP notice I have to write this:
if (isset($_POST['submit']) && $_POST['submit'] != 0) { }
In this particular case I prefer:
if ($_POST['submit']) {}
But here I get the PHP notice.
So which way is the most proper/accepted?
Thank you
isset($_POST['submit']) checks if the submit key is set in the $_POST array. It doesn't just check whether the $_POST array exists and is therefore not "pointless". If you want to check whether the value is not falsey (== false), which includes 0, without triggering an error, that's what empty is for:
if (!empty($_POST['submit']))
which is the same thing as
if ($_POST['submit'])
but without triggering a notice should the value not exist.
See The Definitive Guide To PHP's isset And empty for an exhaustive explanation.
Try
if ($_SERVER['REQUEST_METHOD']=='POST')
{
//do
}
As of PHP version 7 there is a new method available called "Null Coalesce Operator". This method saves you time and space in your code.
$submit = $_POST['submit'] ?? '';
If submit key does not exist or is NULL the value of the $submit variable will be an empty string.
This method is not limited to $_POST. It will work for any variable. For example:
echo $my_message ?? 'No message found';
If message was not initialized or is NULL, the statement above will output No message found
There's even more that you can do with a null coalesce operator, documentation link below.
Documentation here
$_POST[] checks to see if a variable is submitted and not the form name.
if ( isset($_POST['name']) ) {
// work here
}
As per my understanding, It should be like below:
if (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST'){
# if method is post, code goes here.
}
and if you are sure that your method is POST for sure. and you have data post in $_POST you can use code like below:
if (isset($_POST['submit']) && $_POST['submit'] != '') {# I think, '' instead of 0
# if data is posted, code goes here.
}
I usually prefer $_POST.

Checking for a null value in conditional in PHP

I have found there to be multiple ways to check whether a function has correctly returned a value to the variable, for example:
Example I
$somevariable = '';
$somevariable = get_somevariable();
if ($somevariable)
{
// Do something because $somevariable is definitely not null or empty!
}
Example II
$somevariable = '';
$somevariable = get_somevariable();
if ($somevariable <> '')
{
// Do something because $somevariable is definitely not null or empty!
}
My question: what is the best practice for checking whether a variable is correct or not? Could it be different for different types of objects? For instance, if you are expecting $somevariable to be a number, would checking if it is an empty string help/post issues? What is you were to set $somevariable = 0; as its initial value?
I come from the strongly-typed world of C# so I am still trying to wrap my head around all of this.
William
It depends what you are looking for.
Check that the Variable is set:
if (isset($var))
{
echo "Var is set";
}
Checking for a number:
if (is_int($var))
{
echo "Var is a number";
}
Checking for a string:
if (is_string($var))
{
echo "var is a string";
}
Check if var contains a decimal place:
if (is_float($var))
{
echo "Var is float";
}
if you are wanting to check that the variable is not a certain type, Add: ! an exclamation mark. Example:
if (!isset($var)) // If variable is not set
{
echo "Var Is Not Set";
}
References:
http://www.php.net/manual/en/function.is-int.php
http://www.php.net/manual/en/function.is-string.php
http://www.php.net/manual/en/function.is-float.php
http://www.php.net/manual/en/function.isset.php
There is no definite answer since it depends on what the function is supposed to return, if properly documented.
For example, if the function fails by returning null, you can check using if (!is_null($retval)).
If the function fails by returning FALSE, use if ($retval !== FALSE).
If the function fails by not returning an integer value, if (is_int($retval)).
If the function fails by returning an empty string, you can use if (!empty($retval)).
and so on...
It depends on what your function may return. This kind of goes back to how to best structure functions. You should learn the PHP truth tables once and apply them. All the following things as considered falsey:
'' (empty string)
0
0.0
'0'
null
false
array() (empty array)
Everything else is truthy. If your function returns one of the above as "failed" return code and anything else as success, the most idiomatic check is:
if (!$value)
If the function may return both 0 and false (like strpos does, for example), you need to apply a more rigorous check:
if (strpos('foo', 'bar') !== false)
I'd always go with the shortest, most readable version that is not prone to false positives, which is typically if ($var)/if (!$var).
If you want to check whether is a number or not, you should make use of filter functions.
For example:
if (!filter_var($_GET['num'], FILTER_VALIDATE_INT)){
//not a number
}

What is the best way to know is $_GET['example']=="somevalue"?

if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
OR
if((!empty($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
OR just
if($_GET['example']=='somevalue'){ ... }
I am asking that why I have seen many example where people check first if $_GET['example'] is set and then if $_GET['example']=='somevalue' ( first and second example above ).
I don't understand why not just use the last solution ( if $_GET['example']=='somevalue' then $_GET['example'] is obviously set ).
This question refers to any other variable ( $_POST, $_SERVER, ecc ).
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
Is the right one, you want to know that the "variable" exists (or is set) in order to use it. Empty just checks wether it has data of any kind or not.
For example:
<?php
$foo= 0;
if (empty($foo)) { // True because $foo is empty
echo '$foo is either 0, empty, or not set at all';
}
if (isset($foo)) { // True because $foo is set
echo '$foo is set even though it is empty';
}
if (isset($var)) { // FALSE because $var was not declared before
...
}
?>
The differences between isset and empty are subtle but important. They are most relevant when used alone. If you are checking that a variable exists and is a truethy value (e.g. any string that is not all spaces or 0s) you can use either interchangeably.
When to use isset
Use isset when it's important to know if the variable has been defined and is not null:
if (isset($maybeExistsMaybeNull)) {
// variable defined and is not NULL
}
When to use !empty
Use !empty when it's important to know if the variable has be defined and is truthy
if (!empty($mightBeEmpty)) {
// variable defined, and isn't "", " ", 0, "0" etc.
}
!empty is a great shorthand for exists and is something.
When to use array_key_exists
Use array_key_exists when it's important to know if the key exists and the value is of no importance:
if (array_key_exists('something', $array)) {
// $array['something'] exists, could be literally anything including null
}
When not to use isset
If your code looks like this:
if (isset($something) && $something) {
// code is shorter with !empty
}
When not to use !empty
If your code looks like this:
if (!empty($something) && $something === "") {
// you meant isset. this is unreachable.
}
Then you're writing code that can't be executed
Code that throws errors is error prone
Avoid writing code that issues notices/warnings that you are ignoring. For example in the question:
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
The first use of example is an undeclared constant. Or is it undeclared - what if you've got define('example', "foo"); somewhere else in the code.
if($_GET['example']=='somevalue'){ ... }
If the url doesn't contain ?example=.. that's going to issue a notice too.
Writing code without displaying errors means you can very easily miss mistakes like the first.
In context: isset and !empty are equivalent
For the example given, these two language constructs act exactly the same.
There is no case where one will act differently than the other, neither will issue a notice if the variable is undefined, and no measurable difference in performance between the two.
As others have said for checking things like $_GET and $_POST you would ideally want to use:
if ( isset($_GET['example']) && $_GET['example'] =='somevalue' ) {
// process data
}
So you always want to firstly make sure that the variable has been set (and not set to null) or in other words exists. Then proceed to check if the variable contains the data that you were expecting. If you try to make reference to a variable which doesn't exist (by not checking isset()) php will give you a notice saying 'undefined variable...etc etc'.
If you wanted to find out if a variable is set but are not concerned too much by what then you could use:
if ( !empty($_GET['example']) ) {
// process data
}
But I would be careful about using empty() on strings in this regard as empty can behave strangely with string data like '0' or ' '.
So I would always do the first one, to a) make sure the variable exists and b) is what you were expecting it to be.
This is something that you'll probably do a lot of and it helps to put together a class/functions which handles this checking for you so you dont have to do it everytime.
function checkValue($key, $value) {
if(array_key_exists($key, $_REQUEST)){
if ($_REQUEST[$key] == $value) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I just use Request as a default instead of switching out (though it is preferable to switch in some cases between POST and GET for security (imo)).
Now you can just call this function anywhere
if (checkValue('Item', 'Tom') === true){} etc
the best is
if((isset($_GET[example]))&&('somevalue'==$_GET['example'])){ ... }
The difference between
'somevalue'==$_GET['example']
AND
$_GET['example']=='somevalue'
If you mistype the == and type = instead, the first notaion will raise an error to notify you.
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }

Determing whether a $_POST["X"] is null

How would I determine if a $_POST is null? I want to do an if/else based on whether an ID is submitted or not, to determine whether a record should be inserted into a MySQL database, or updated.
Would I use isset($_POST["ID"]) ?
There are several functions in php for this.
People use empty or isset for this purpose. Many use the one and dont think about the difference.
This example from the documentation shows clearly the difference.
$var = 0;
// Evaluates to true because $var is empty
if (empty($var)) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if (isset($var)) {
echo '$var is set even though it is empty';
}
In this particular case, you should use empty and not isset, because the variable can be set, but empty.
you need to use empty():
if (!empty($_POST["ID"])) {
//rest of code here
}

Categories