Why do i need to almost use Isset? - php

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.

Related

Why should i use isset? [duplicate]

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.

how to set a PHP variable if nothing has been posted to it yet?

I have a PHP graphs page that displays graphs generated from another PHP file.
This graph generating PHP file will have its variables changed through an AJAX script.
When the PHP graphs page first loads i need to be able to identify whether a variable in the generating PHP file is empty so i can change it to a default value until data overwrites it through the $_get function.
I have tried this so far with no luck and am a bit stuck, any assistance would be greatly appreciated as i am very new to PHP. thanks :)
$course = $_GET['usercourse'];
if (empty($course))
{
$course = 'All';
}
else
{
}
Use the isset() function.
if (isset($_GET['usercourse'])
{
//do something
}
Use isset() function.
if (isset($_GET['usercourse'])
{
//do something
}
Use isset function, like this,
if(isset($_GET['usercourse']))
$course = $_GET['usercourse'];
if (empty($course))
{
$course = 'All';
} else {
//do something...
}
Naive code example that checks if the variable was set and it is not equal to empty string:
$course = isset($_GET['usercourse']) && $_GET['usercourse'] !== ''
? $_GET['usercourse']
: 'All';
Slightly better:
$course = isset($_GET['usercourse']) && preg_match('#^(LIST|of|AccEPtabLE|vaLUes)$#i', $_GET['usercourse'])
? $_GET['usercourse']
: 'All';
$course = isset($_GET['usercourse']) && in_array($_GET['usercourse'], array('list', 'of', 'acceptable', 'values'))
? $_GET['usercourse']
: 'All';
Even better:
Use Filter Functions.
Other answers have answered your direct question, but I think there's something deeper here that should be explained.
You typically want to avoid accessing array indexes that you are not certain exist.
For example:
$a = array('foo' => 'bar');
echo $a['test']; //bad!
The same applies for $_GET, $_POST, $_COOKIE, etc. Don't access indexes unless you know that they exist.
Note that for user defined indexes, this translates to "don't access indexes unless you've checked that they exist."
$content = $_GET['content']; //ALWAYS wrong
You have three options for checking array indexes: isset, empty, and array_key_exists.
isset($x) returns true iff $x is non-null. isset is essentially equivalent to: $x !== null, except isset will not issue undefined index/variable notices.
(empty($x) === (!isset($x) || !$x))
In other words, empty consider anything loosely equal to false to be empty. This is useful in certain situations.
array_key_exists($key, $array) is a simple guarantee that $array[$key] will not issue an undefined index notice.
So what's the easiest way to extract user input in a proper manner?
$content = (isset($_GET['content'])) ? $_GET['content'] : null;
You have an imporant guarantee at this point in that $content !== null iff the user provided input.
Note that you should also avoid ever having an excecution path that leaves a variable undefined:
if (isset($_GET['content'])) {
$content = $_GET['content'];
}
echo $content; //WRONG - $content is not guaranteed to be defined
You could use $content in that situation if it were wrapped in isset or empty, but that hampers the readability of code. If you want to leave a variable undefined under some condition, define it as null. That leaves it as 'undefined' without it issuing variable doesn't exist warnings.
$a = null;
var_dump($a === $b); //true, because the non-existent $b is treated as false
//(note that this is terrible style though -- this would issue a variable doesn't exist warning for $b
There's also, of course, PHP's filter extension. In particular, you can use filter_input to avoid rewriting a lot of the code for handling user input.
You can read more about proper (or, paranoid, as some may call it) input handling here or here in the proper sections.
As an aside, you should always develop with errors cranked all the way up, and you should be monitoring for any kind of error (warning, notice, etc). This will help prevent potential logical bugs, and it tends to keep code clean. (There seems to be a correlation between code that never issues notices and well written code.)
why not compare against an empty string?
if (!isset($course) || empty($course) ) {
$course = 'All';
}

I'm confused about the flow of $_POST[] variables and regular variables

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.

Undefined variable when checking if variable is defined in Kohana view

I'm running into this error when loading up my view:
ErrorException [ Notice ]: Undefined variable: errors
APPPATH\views\admin\category\add.php [ 2 ]
<h3>Add</h3>
<?php if( $errors ): ?>
<p><?=$errors?></p>
<?php endif; ?>
How is my checking not valid?
You might want to give this one a try:
isset Manual
or you can actually show the controller code in which you're failing to set the errors to the View object (probably inside of a condition).
As Kemo said you should use isset. What you are actually doing there is checking if the variable $errors has a value that evaluates to true/false. The non-existence of the variable does not equate to false and you wouldn't want it to, you want spelling mistakes etc... to throw errors rather than any variable just being considered null regardless of whether it's actually been declared. isset is specifically designed to check for the existence of the variable. As you still want to check if it also evaluates to true you should be doing:
if(isset($errors) && $errors)
An undefined variable means it does not exists. You can just wrap it inside isset() to do what you want to do:
<?php if( isset( $errors ) ): ?>
Isset is one of the few language constructs that work on unset variables without giving a warning / error. Another one is empty().
PHP is throwing an error because the error reporting includes the E_STRICT constant, which throws an exception if an undefined variable is pointed to.
Use isset() instead - It's good practice to check if your variable even exists (if there's a chance that it doesn't).

getting true/false value returned from a checkbox, error when false

Please note that I am just beginning to learn php. I've gone through a few different multi-day tutorials and I'm now trying to write a small mailing list script on my own. This, I'm sure, is a ridiculously simple question/answer, but no way in which I've figured out how to word the question has turned up any results on google.
i have a checkbox named "htemail", when i send it to the script i have this code:
if(!$_POST['htemail']){
$usehtml = 0;
}else{
$usehtml = 1;
}
echo($usehtml);
if the checkbox is checked, it returns 1, but if it's not I get the following error:
Notice: Undefined index: htemail in
C:\wamp\www\mailing
list\createUser.php on line 7 Call
Stack #TimeMemoryFunctionLocation
10.0004673576{main}( )..\createUser.php:0 0.
The first thing I thought to do was to flip the code around backwards so it checks for the existance of the check first (I'm not sure why I thought this would help)
Thanks in advance for any answers.
The browser might not include in the post data if it's not checked. Use the function isset to check on it. If is not set, mean it's not checked, the other way around is not true, if set, might still be false.
if(isset($_POST['htemail']) && $_POST['htemail'] == "Value"){ //where "Value" is the
//same string given in the HTML form, as value attribute the the checkbox input
$usehtml = 1;
}else{
$usehtml = 0;
}
As an alternative to isset you can use array_key_exists
What you want is to detect the existence of the array member, then check it's contents:
$usehtml = 0;
if (isset($_POST['htemail']) && strtolower($_POST['htemail']) == 'yes'){
$usehtml = 1;
}
echo($usehtml);
isset() checks to make sure the array member exists, in which case you can then check to make sure the value evaluates to your required value.
Additionally, above I've ordered the evaluation to default to a value (0), then change to another value if another variable is present. There really isn't a big difference between doing this and an if/else statement, but I think it's cleaner to read and understand.

Categories