I have a simple form I created, and in it I have the following checkbox:
<input type="checkbox" name="test">
Note: this form is being submitted to itself.
Above the form, I have the following PHP:
if (empty($_POST['test'])) {
$thevalue = 0;
} else {
$thevalue = 1;
}
var_dump($thevalue);
When I process the form, I get what I would expect. If I check the box and submit, I get int(1) if I leave it unchecked I get int(0).
In the first line of my PHP code, I wanted to replace $_POST['test'] with some simple variable.
So I added the following line above my code:
$simplevar = $_POST['test']
I then replaced the condition in my if statement to be empty($simplevar)
But when I submit the form, I get a "Notice: Undefined index:" error message
Why is this happening?
Assuming it's possible to achieve what I was after (i.e. insert $_POST into $simplevar), how might I go about it?
Thanks in advance for your help!
PS: I may have a follow up to this question, but didn't want to clutter things by jamming it all in here.
Thanks again... oh, and Merry Christmas! ;-)
This happens because when you don't check the checkbox, the browser does not send any value to server for that control when the form is submitted. Because of this, $_POST['test'] is not defined, and you tried to use it without a check as to whether it existed, so you get a warning. One of the checks that empty() does is to see whether the value is set. So, when you use the $_POST keys directly in empty(), you don't get an error, but when you try and use it in an assignment without this check, you will get the error.
You can do roughly what you want to do, you just have to change the logic slightly. If you do:
$simplevar = !empty($_POST['test']);
// You could also do
// $simplevar = isset($_POST['test']);
if ($simplevar) {
// The box was checked
} else {
// The box was not checked
}
...it will do what you want without the error. Using this approach, $simplevar always holds a boolean indicating whether or not the box was checked.
When a checkbox is unchecked, it's not added to the $_POST array as a key, which is why $simplevar = $_POST['test'] returns the error you posted. Using empty() gets past this problem by empty() handling errors better (well, silently at any rate).
You haven't specified whether you get that error when the checkbox is checked or not, but the above explanation is the only one I can give. If you're unsure, try doing print_r($_POST) to see what $_POST actually contains.
A solution to your problem would be to use a ternary expression to handle the error a little better:
$simplevar = isset($_POST['test']) ? 0 : 1;
This will assign 0 to $simplevar if $_POST['test'] isn't set (checkbox isn't checked), or 1 otherwise.
Do make sure all your form processing code is put inside
if(!empty($_POST)) {
// Code
}
So that it's not executed every time the page loads, otherwise your error will show every time.
Checkbox values are only transmitted if the checkbox was checked. This means that unchecked checkboxes won't appear in the $_POST array.
A way to suppress the notice from PHP is to use a reference instead of a variable:
$simplevar =& $_POST['test'];
if(empty($simplevar)) $thevalue = 1;
else $thevalue = 0;
That's expected behaviour. If you are assigning the variable like this:
$simplevar = $_POST['test'];
Then the $_POST variable might be absent. The Zend runtime then assigns the NULL value, but gives you a useful debug hint, should that not be what you wanted.
When you used empty() before, the check for variable existence was built in. empty() is a language construct. Like isset() it's often used to eschew such notices. The cumbersome syntax to emulate such language behaviour is:
$simplevar = empty($_POST['test']) ? NULL : $_POST['test'];
The language built-in for is:
$simplevar = #( $_POST['test'] );
Now, I will get roasted for mentioning it. (Using # is useful if you want to bring the debug notices back at some point, while the empty and isset constructs eternally suppress them.)
First, you should always check that variables in $_POST, $_REQUEST, and $_GET are set before attempting to use them. Always handle the condition where they are not set even if you simply output an error.
Because the error is an undefined index it seem the error is in test not being set in $_POST, though that doesn't make a lot of sense. I would add a check, maybe an echo or var dump to check $_POST. If it is set the other problem could be an issue with scope. $_POST is something called a super global which makes it available in any scope. Variables you set you may need to make global by defining them as such if you want to access them across scopes.
Related
Knowing the differences of array_key_exists() and isset() in PHP, I see a lot of advocates on the web suggesting for replacing array_key_exists() with isset(), but I am thinking is it safe to do so?
In one project, I have the value of $var submitted by users. The value can be anything, even NULL or not set at all. I want to use !empty($var) to check if $var holds a non-empty value, but I understand that using !empty($var) alone is dangerous since if $var isn't pre-defined, PHP will throw an error.
So I have isset($var) && !empty($var) for checking whether $var holds a non-empty value.
However, things get complicated when I have a value stored in an assoc array. Compare the followings, assuming array $arr always exists but the key foo may or may not exist in $arr.
// code snipplet 1
$arr = array();
echo isset($arr['foo']);
// code snipplet 2
$arr = array();
echo array_key_exists('foo', $arr) && !is_null($arr['foo']);
Code snipplet 2 will always work but it seems clumsy and harder to read. As for code snipplet 1, I had bad experience... I wrote something like that before in the past on a development machine. It ran fine, but when I deployed the code to the production machine, it threw errors simply because key didn't exist in array. After some debugging, I found that the PHP configs were different between the development and the production machines and their PHP versions are slightly different.
So, I am thinking is it really that safe to just replace array_key_exists() with isset()? If not, what can be of better alternatives of code snipplet 2?
In one project, I have the value of $var submitted by users.
How does that work? Users shouldn't be able to set variables. They should be able to, e.g., submit form values which end up in $_POST. I repeat, they should not be able to directly create variables in your scope.
If "users" here means some sort of plugin system where people write and include PHP code… then you may want to think about defining a more stable interface than setting variables.
The value can be anything, even NULL…
Not if it's a value submitted through HTTP. HTTP has no concept of null. It's either an empty string or doesn't exist at all.
using !empty($var) alone is dangerous since if $var isn't pre-defined, PHP will throw an error
That is wrong. empty specifically exists to test a variable against false without throwing an error. empty($var) is the same as !$var without triggering an error if the variable doesn't exist.
So I have isset($var) && !empty($var) for checking whether $var holds a non-empty value.
See Why check both isset() and !empty(). (Spoiler: it's redundant.)
echo isset($arr['foo']);
echo array_key_exists('foo', $arr) && !is_null($arr['foo']);
These both do exactly the same thing. isset returns true if the value exists and its value is not null. The second line returns true if the array key exists and its value is not null. Same thing.
I had bad experience...
You'd need to be more detailed about that, since there should be no caveat to isset as you describe it.
See The Definitive Guide To PHP's isset And empty and Difference between isset and array_key_exists.
This question already has answers here:
Weak typing in PHP: why use isset at all?
(9 answers)
Closed 7 years ago.
I'm beginner in PHP and was wondering what's the difference between this
$variable = "text";
if($variable){
echo $variable;
}
and this
$variable = "text";
if(isset($variable)){
echo $variable;
}
Sometimes you want to know if a variable is set or not e.g. for security reasons of for debugging reasons.
The function isset() is used to determine if a variable is set and is not NULL and is accordingly returning true or false.
The expression if($variable) {} instead will evaluate to false if $variable is set but is zero or if $variable is set but its current value is false (=counterexample)
Assume:
isset($variable): Evaluates to true if a variable is set and not null
if($variable): Evaluates to true depending on the value of a variable or the result/value of an expression
The most important feature of functions like isset(), empty(), etc. to me is, that they do not throw errors when a variable is not set, like Marc B already mentioned.
PS: I strongly recommend to turn on strict mode and all error reporting during development.
isset is used to check whether input you receive contains what you expect - this is a very, very loose definition and I wrote that trying to explain easily when you'd use it.
When you set a variable yourself, then it doesn't make sense to use isset, you know it's set and that it contains some value.
However, many languages, not just PHP, deal with user input. User in this case could be a human, another computer service etc. You usually store that input inside a variable. A great example is PHP's $_POST, $_GET, $_SERVER, $_SESSION.
When you receive an input that user made via HTML form, you want to check whether certain values have been populated - in that case, you use isset.
An example HTML form:
<form method="POST" action="your_file.php">
<input type="text" name="first_name" />
<input type="text" name="last_name" />
<button type="submit">Send</button>
</form>
Someone can submit that form, they can fill in both inputs. Or only one of them, or even none. You don't know what they've done, but regardless - PHP will provide you with a variable that might contain correct input.
If I submitted that form with nothing filled in, and if you tried to access a value for first_name - you would get a PHP warning - and you don't want PHP warnings.
Therefore, before working with user input (in this case with a $_POST superglobal array), you would check whether I filled in everything properly and you'd do that with:
if(isset($_POST['first_name']) && isset($_POST['last_name']))
{
echo "Form was filled in correctly";
}
else
{
echo "Form wasn't filled in correctly! Please fill in both fields";
}
Hopefully that clears it up a bit. Just once more, I used very trivial but real-world examples.
Perhaps you example is a bit skewed. However. if you were to ignore the first line of each code segment, perhaps you will see this differently. Consider the code segments
if($variable){
echo $variable;
}
If $variable has not been initialised and assigned a value, then the is statement will result in an error.
On the other hand, if you initialise the variable
$variable = "text";
if($variable){
echo $variable;
}
will test is the variable is true, or non zero.
The isset() function will ignore the value, and tell you if the variable is initialised.
In the following code segment, the if() statement will return true.
$variable = "text";
if(isset($variable)){
echo $variable;
}
while, in this code
<?php
if(isset($variable)){
echo $variable;
}
the if() statement will return false.
Why every time I need to almost use isset() I couldn't understand why the php always has notice and warnings following is the two codes and I don't understand why we need to isset().
Please explain briefly because I'm a low thinker as you can see I declare the variable x but the PHP said undefined this is only in checkbox and radio button didn't encounter in textbox and even in declaring variable we need to declare it at the top like this $var='';
Please explain my mind is in confusion right now I don't know what is true or false I know isset is use to check if the variable is set or null but why it is important. Why in checkbox it doesn't give me error HERE IS THE ERROR WITHOUT ISSET()
WRONG CODE
<?php
if(isset($_POST['Submit'])){
$x=$_POST['burger'];
if($x == ''){
echo 'Please fill it up';
}else{
foreach($x as $z){
echo $z.'<br>';
}
}
}
?>
RIGHT ONE
<?php
if(isset($_POST['Submit'])){
if(isset($_POST['burger'])){
$x=$_POST['burger'];
}
if(empty($x)){
echo 'Please fill it up';
}else{
foreach($x as $z){
echo $z.'<br>';
}
}
}
?>
Php isset() is used to check whether a variable is set or not. So without isset check, $x is not defined which results in error.(uninitialized variable $x).
Explanations below,
if(isset($_POST['Submit'])){ //checks if $_POST["submit"] is set, preventing $_POST uninitialized errors
if(isset($_POST['burger'])){ //checks if $_POST["burger"] is set, preventing $_POST uninitialized errors
$x=$_POST['burger']; //$x will be always set, bcoz its inside isset($_POST["burger"])
}
if(empty($x)){
echo 'Please fill it up';
}else{
foreach($x as $z){
echo $z.'<br>';
}
}
}
When you try to access a variable in PHP which wasn't initalized before, there will be a warning issued. So isset() is used to check if the variable exists or not.
But there is a problem with your solution, because in case when $_POST['Burger'] isn't set, $x will also not be set, it will be better to use if(isset($x)){ instead of if(empty($x)){
$_POST is an array. Normally, when you try to access a key of an array that doesn't exist, you get an error. isset allows you to check if the key exists. That way you can write an if that throws a human readable error or uses a default value in case the posted value doesn't exist.
In alternative to isset, you could use:
if (array_key_exists('Submit', $_POST)) {
}
isset is more a generic way to perform the check, and it's often used for this goal. But it has some side effects too! It can for instance return false, even if the key technically exists.
By using a specific function like array_key_exists, your code is a bit more verbose and more specific, making it easier to understand what is going on, and you won't have those forementioned side effects.
i recently had to do a "test" for a job, and i got feed back saying that this statement was incorrect:
$images = $flickr->get_images(5, !empty($_GET['pg']) ? $_GET['pg'] : 1);
The "supposed" error was generated via the ternary operator on the first time the page was loaded, as there was no "?pg=1" (or whatever) passed via the query string.
The feed back said i should have used isset instead. I have looked at various posts both here (question 1960509) and blogs, but cannot find any definitive answer.
Is this really an error? How can i replicate this issue? do i need to put on E_STRICT or something in my php.ini file? Or might this be due to an older version of php?
Note: please don't tell me about how i should validate things.. i know this... it was a test to just see if i could use the flickr api calls.
This is perfectly fine. empty is not an actual function, it's a language construct. It does not issue a warning if a variable is not set (in that case the variable is considered empty, thus the 'function' returns TRUE just as you want), and additionally it checks for empty or zero values.
You could see empty as a normal isset check with an additional loose comparison to FALSE:
empty($var) === (!isset($var) || $var == FALSE)
$images = $flickr->get_images(5, (isset($_GET['pg']&&($_GET['pg']))) ? $_GET['pg'] : 1);
without isset you'll get error so combine them
I'd use
$images = $flickr->get_images(5, array_key_exists('pg', $_GET) ? $_GET['pg'] : 1);
Combine with !empty($_GET['pg']) if needed (i.e. array_key_exists('pg', $_GET) && !empty($_GET['pg'])), but array_key_exists is the intended function for this job.
I think in a situation like this isset is the correct function to use as it is checking the existence of the array element rather than checking if the value of the element has been set. As Martin notes, the best thing to do here is combine them as this will only check the value if the element exists, meaning that the error will not occur on the first page load.
Also, I think this will only give a warning if E_NOTICE is on (or perhaps E_WARNING as well)
The reason you would get an error is because the empty function is designed to check the value of an existing variable, whearas isset() is designed to tell you whether a variable has been instantiated, however because empty() is a language construct technically it doesn't throw an error or create a warning so most people don't see the difference.
From the docs:
empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set.
isset — Determine if a variable is set and is not NULL. So "isset" is the correct function to use for checking for value is set or not.
More details :http://php.net/manual/en/function.isset.php
In a php page I have following code:
if($_REQUEST['c']!="") // I get error on this line itself. Why?
{
$pidis=(int)($_REQUEST['c']);
}
I keep getting Undefined index error.
On Googling I manage to understand that if a page is access without parameters (in URL) which we are trying to access we can get this error/warning. I believe that if a parameter is not defined in the URL it should just return empty instead of giving error/warning message.
I know that it is possible to suppress errors and warning by adding
error_reporting(E_ALL ^ E_NOTICE);
But I do not want to do this.
This same page work just fine on our company's web server but does not work on our clients web server.
Why is this happening?
How to solve this problem?
You are getting that error because you are attempting to compare $_REQUEST['c'] to something when $_REQUEST['c'] does not exist.
The solution is to use isset() before comparing it. This will remove the warning, since the comparison won't happen if $_REQUEST['c'] doesn't exist.
if(isset($_REQUEST['c']) && $_REQUEST['c']!="")
{
$pidis=(int)($_REQUEST['c']);
}
It is an E_NOTICE level error, and your level of error reporting will affect whether the error shows up or not. Your client's server has E_NOTICE level error reporting turned on, which is why it shows up there.
It is a good idea to always develop using E_ALL so that you can catch this kind of error before moving your code to other servers.
Another solution is to use the following:
$pidis = isset($_REQUEST['c']) ? $_REQUEST['c'] : '';
You can also, if you prefer to return a value other than empty, by placing a default value within the final set of single quotes, e.g.
$pidis = isset($_REQUEST['c']) ? $_REQUEST['c'] : 'Default Value';
or return a different variable type, for instance an integer:
$pidis = isset($_REQUEST['c']) ? $_REQUEST['c'] : 34;
Instead of isset() you can also use: array_key_exists().
The difference between both methods is that isset() checks also whether the value of the variable is null. If it is null then isset returns false whereas array_key_exists() returns always true if the key exists (no mater which value). E.g.:
$array = array('c' => null);
var_dump(isset($array['c']))); // isset() returns FALSE here
var_dump(array_key_exists($array['c']); //array_key_exists() returns TRUE
Depending on the context, it is important to distinguish this. In your case I don't think it matters doesn't matter, as (I guess) a request parameter never will be null (except one overwrites it manually).
Use isset($_REQUEST['c']) to test if it exists first.
PHP is giving a notice (which is not an error : it's just a notice) when you are trying to use a variable that doesn't exists, or an array element that doesn't exist.
This is just to help you, and you should not mask those notices : they are here to help you -- for instance, to help you detect typos in variable names.
Before using that array index, if it's not always present, you should test if it's here, using isset :
if (isset($_REQUEST['c']) && $_REQUEST['c']!="") {
// ...
}
Clean way could be :
$pidis = $_REQUEST['c'] ?? null
this is same as checking isset request but shorter.