I noticed this weird evaluation yesterday after searching for a few hours in my code for an error. i am passing scores into php, sometim开发者_Go百科es the score=0 which causes an issue.
send php ?blah=blah&score=0
if(!empty($_REQUEST['score']){
//do database update stuff
}else{
// show entire webpage
}
It works great unless the score=0 the if() will evaluate to false and return the entire webpage to my ajax handler and error. I have temporarily changed !empty to isset but this will cause problems in the future because isset evaluates to true even if the score key is in the url string without a value.
ex: (?blah=blah&score=&something=else)my question is: what is the best way to recode this to work correctly now and in the future?
edit: there are a few working answers here, i appreciate everyones time. it was difficult to choose an answer
As the manual says, a variable is considered empty()
if it has an empty or zero value.
So it will treat your variable wrongly as empty even though 0
is a perfectly acceptable value in your case.
If you need score
to be a number, you could use isset()
in combination with a is_numeric()
check instead:
if((isset($_REQUEST['score']) and (is_numeric($_REQUEST['score'])){
Check out the manual page to see the kinds of values is_numeric()
accepts. If score
is always an integer, you can also use is_int((int)$_REQUEST['score'])
but that will convert invalid input values to 0
.
Additionally, as @sightofnick says, it's better to use explicit $_GET
or $_POST
instead of $_REQUEST
.
Re your update:
In that case I would
- Do check whether the variable is
"0"
(string "zero") - If it is
"0"
, make it0
(integer "zero") - If it is not
0
, convert it to an integer(int)$_REQUEST["score"])
- If the conversion resulted in
0
, it was invalid input - exit - You have a valid integer variable.
empty() will return false
if a value is zero. Use isset() or array_key_exists() instead, if you want to check if a variable in an array is set:
if (array_key_exists('score', $_REQUEST)) {...}
Try doing
if (isset($_REQUEST['score']) && ($_REQUEST['score'] !== '')) {
...
}
The isset will handle the presence/absence of the query parameter, and the strict string (!==) comparison will handle the case where the 'score' query is present but has no value. PHP treats all data coming from _GET/_POST/_REQUEST as strings, so this test is 100% reliable.
if(isset($_REQUEST['score']) && $_REQUEST['score'] != ''){
//do database update stuff
}else{
// show entire webpage
}
You may be able to solve that with
if (isset($_REQUEST['score']) && is_numeric($_REQUEST['score'])) {}
That of course if scrore can only contain numeric value
精彩评论