Reputation: 1039
I want to make a function for a "secure" php page that will check the token(the one passed by post and the one from the session).
But I don't want to write two if statements like this:
function CheckToken(){
if(isset($_POST['token']) && isset($_SESSION['token']))
if($_POST['token']==$_SESSION['token']) return true;
return false;
}
Can I do something like this(?):
function CheckToken(){
if(isset($_POST['token']) && isset($_SESSION['token']) && $_POST['token']==$_SESSION['token']) return true;
return false;
}
Here's all about the order in which those functions are executed (when using the and operator).So if you're using the AND operand then if the first conditions is false don't evaluate the second. I remember that vb.net had a solution to this problem(evaluating only the first function-if it is false don't evaluate the second one).
So, is it safe to put everything on a single line(like I did in the second example)?
Upvotes: 1
Views: 1182
Reputation: 8059
PHP does the same thing as the usual if
statement evaluation in other major languages, that is, check from left to right.
So if you have
if (cond1 && cond2 && cond3)
Scenario 1:
If cond1
is true, it will then execute cond2
, and then cond3
.
Sample: https://3v4l.org/Ap9SQ
Scenario 2:
If let's say cond2
is false
, then cond3
will be ignored.
Sample: https://3v4l.org/u9P4O
Same goes to OR
if (cond1 || cond2 || cond3)
If cond1
is true, cond2
and cond3
will be skipped.
Sample: https://3v4l.org/ZAZcD
So since your function is just returning true
or false
, you can even simplify it to something like this:
function CheckToken() {
return isset($_POST['token']) &&
isset($_SESSION['token']) &&
$_POST['token'] == $_SESSION['token'];
}
Split lines for readability. Also checkout isset
manual as you can pass in multiple variables for empty checking.
Upvotes: 3
Reputation: 119
Yes, there really is no difference to changing the order like that. It is perfectly safe, because all it's doing is changing the look of the script while the execution is the EXACT same.
It would be best to do the second option.
Upvotes: 1