Using isset($_REQUEST["p"]) or $_REQUEST["p"] - php

Sometime ago, I was in a internship, and I was working as a junior web-developer. While working and learning, I noticed that when changing pages, instead of using isset($_POST/GET/REQUEST["var"]) they just used $_POST/GET/REQUEST["var"].
So, later I came home, and tried the same thing. What happens ? Every-time I come across a if() to verify that, I have to use isset(), otherwhise it gives me an error. But notice one thing, my url is this:
?p=sub_artigo&id=2
So, when I do the if() condition:
if(isset($_REQUEST["p"])=="procurar" && $_REQUEST['cont']){
It doesn't show errors, but if I take of the isset(), it gives the usual error that I see in the forums and here.
So my question is, why doesn't show the error for the second variable ?
Note: p->string;id->int

They have error_reporting turned down, which is nice because it means you can do things like
if ($_POST['whatever']) { ... }
instead of
if (isset($_POST['whatever'])) { ... }
but it also stops you from seeing other possibly pertinent errors.
this setting is found in the php.ini file under the variable error_reporting.
More information on the ini file can be found here: http://php.net/manual/en/ini.php
also, isset($_REQUEST["p"])=="procurar" while sytactically correct, is never going to return true, because isset() returns a boolean value.
what you want is isset($_REQUEST['p']) && $_REQUEST['p'] == 'procurar'

RTM: http://php.net/isset
isset() returns a boolean TRUE/FALSE. It will NEVER return a string, so this statement
if(isset($_REQUEST["p"])=="procurar" && $_REQUEST['cont']){
can NEVER succeed, because isset() will never EVER be equal to procurar, so the ['cont'] check will never be evaluated.

When the first statement is false, PHP does not bother triyng the rest of the if statement.
I always use the following check on every $_REQUEST, $_POST or $_GET key:
function ifSet($key) {
return (isset($_REQUEST[$key]) && $_REQUEST[$key])?$_REQUEST[$key]:'';
}
This will never give you any warnings, even if error_reporting is set to E_ALL.
The 'isset' checks if the $key is set and after that it checks if $key has a value.

Related

Should I check isset($_GET[...]) when I expect it to always be set?

I was recently placed on a project with some PHP, and I don't know much about PHP. There are a couple instances in the site where upon clicking a button, the user is redirected to another page with some URL parameters. The next page then uses $_GET to get those parameters and move on.
Another issue in the code caused the page to reload the second page without the parameters, so using $_GET would return errors, but with the other issue fixed, I can't think of a reason why the parameters wouldn't be there.
While debugging, I came across advice to always check $_GET using isset(), but theoretically there should never be an instance when those parameters aren't there (otherwise something else is really wrong with the server or the code).
Is it still worth putting in the checks and working out a backup solution, even though there shouldn't be a need for it? I want to make sure I'm not ignoring some other potential issue that I may not be aware of.
It is always good practice+recommended to check your variables before applying any logic.
!empty() is recommended to use instead of isset() because it check both that variable is initialized and have some values too.
In case of array count($array)>0 can be used as a check.
Why to use !empty() check here:- !empty() Vs isset()
If you are expecting or requiring data to be sent via $_GET you should check if it's set. Especially since that data can be easily manipulated. Also like #Alive to Die said !empty() is better.
isset() checks if a variable has a value including ( False , 0 , or
empty string) , but not NULL. Returns TRUE if var exists; FALSE
otherwise. On the other hand the empty() function checks if the
variable has an empty value empty string , 0, NULL ,or False.

isset or !empty for $_GET[var]

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

PHP isset() redundant in this context?

I am going through the "Head First PHP & MySQL" book right now, and on many parts of the book there are code snippets used to process HTML forms. They start like this:
if (isset($_POST['submit'])){
...
}
The if clause is used to detect if the form has been submitted already or not. Being used to programming in C mostly, I find that construct redundant and annoying (and I also don't think it helps code readability for experienced programmers). I would rather write it as:
if ($_POST['submit']){
...
}
Question: Is there some other reason to use isset() in this context that I might be missing? Would my version of the snippet be considered non-idiomatic PHP? What about in other contexts, can you give me an example of when isset() might be useful?
There are situations where a variable is NULL, 0, or FALSE. They'd fail the if() {} comparison, but they are set.
Using isset() also avoids a notice about an undefined variable if your error_reporting settings include E_NOTICEs.
Check out this page for more information about isset()
http://php.net/manual/en/function.isset.php
Well, if $_SERVER doesn't have the submit key, the second block would throw an E_NOTICE (Undefined index), therefore you should use isset() if you want to check if that key exists and is not null (or, alternatively, array_key_exists(), which just check for the existence).
Additionally, if you also want to check the content of the variable (for example, if it's set to false or 0), I'd suggest to use the !empty() (note the negation with !) function instead of isset().
One of the biggest reasons I can think of is because of PHP's error_reporting and display_errors setting.
Let's say that error_reporting is set to E_ALL and display_errors is turned on.
If you tried to do something like: if ($array['iDontExist'] == false) the code will run as expected, since the variable isn't set, it will evaluate to boolean false. The side effect however, is that PHP will emit a notice saying the variable $array['iDontExist'] does not exist. The more you have this, the more likely random notices will be spammed all over the output.
I find a LOT of production systems have error reporting turned on which would result in this unwanted behavior. If display_errors is turned off, the messages won't show up in the browser, but if error_reporting is set to track notices, the error_log will contain all of the notices about undefined variables, which is also an annoyance.

Is this an OK test to see if a variable is set

Yesterday, I posted an answer to a question that included several (unknown to me at the time) very bad code examples. Since then, I've been looking at my fundamental knowledge of PHP that allowed me to think that such code is possible. This brings me to a question that I can't seem to find an answer to:
If I want to check for whether or not a variable has anything set, is it a valid practice to not use isset() or another helper function? here's a "for instance":
if($not_set){
//do something
} else {
//do something else
}
Rather than...
if(isset($not_set)){
//do something
} else {
//do something else
}
From the name of the variable, you can see that this variable is not set. Therefore the conditional would be false and the else portion would run. Up until now I have been using this practice, but after the posts yesterday, I now have an inkling that this is wrong.
Here's why I thought that it would be an ok practice to leave out the isset() function above. From PHP manual:
The if construct is one of the most
important features of many languages,
PHP included. It allows for
conditional execution of code
fragments. PHP features an if
structure that is similar to that of
C:
if (expr) statement
As described in the section about
expressions, expression is evaluated
to its Boolean value. If expression
evaluates to TRUE, PHP will execute
statement, and if it evaluates to
FALSE - it'll ignore it. More
information about what values evaluate
to FALSE can be found in the
'Converting to boolean' section.
And from the 'Converting to boolean section':
When converting to boolean
, the following values are considered
FALSE:
...
* the special type NULL (including unset variables)
Why would the manual go out of its way to state that unset variables are included if this is a bad practice? If it's unset, it gets converted to NULL and therefore is evaluated properly by the conditional. Using isset() will find the same result, but will take extra cycles to do so.
Have I been wrong this whole time, and if so, why? (And just how bad it is, maybe?)
If the variable is not set you get a Notice. If you use isset() you don't get a notice. So from an error reporting point of view, using isset() is better :)
Example:
error_reporting(E_ALL);
if($a) {
echo 'foo';
}
gives
Notice: Undefined variable: a in /Users/kling/test on line 5
whereas
error_reporting(E_ALL);
if(isset($a)) {
echo 'foo';
}
does not output anything.
The bottom line: If code quality is important to you, use isset().
It's okay but not good practice to use if to check for a set variable. Two reasons off the top of my head:
Using isset makes the intent clear - that you're checking whether the variable is set, and not instead checking whether a condition is true.
if ($not_set) will evaluate to false when $not_set is actually set but is equal to boolean false.
You will run in to problems if your variable is set, but evaluates to FALSE, like the following:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the
string "0"
an array with zero elements
an object with zero member
variables (PHP 4 only)
the special type NULL (including
unset variables)
SimpleXML objects created from empty
tags
Taken from the PHP manual.
Basically, using isset() is showing that you are explicitly checking if a variable exists and is not NULL, while the structure of your if statement only checks if the variable is true. It is more clear and less error-prone.
It is a common practise, but is not good -- you should always use isset!
If your $not_set is set, and is a bool with the value false, your "test" will fail!
isset works as a guard preventing you from using variables that do not actually exist.
if (isset($foo)) and if ($foo) do not mean the same thing. isset just tells you if the variable actually exists and if it's okay to use it, it does not evaluate the value of the variable itself*.
Hence, you should usually use one of these two patterns:
If the variable is sure to exist and you just want to check its value:
if ($foo == 'bar')
If the variable may or may not exist, and you want to check its value:
if (isset($foo) && $foo == 'bar')
If you're just interested that a variable is set and evaluates to true, i.e. if ($foo), you can use empty:
if (isset($foo) && $foo)
// is the same as
if (!empty($foo))
* it does check for null, where null is as good as not being set at all

Undefined index: Error in php script

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.

Categories