In my project, I have a wrapper class for $_SESSION, so session variables can be accessed by $session->var. I was trying to check if session variables were set or not using isset:
if (!isset($this->session->idUser)) {
...
}
but isset is not returning anything. So in my wrapper class I wrote the following function to test what was going on.
public function isItSet($var)
{
die(isset($_SESSION["id"]));
}
this results in an empty page. I tried:
public function isItSet($var)
{
die(is_null(isset($_SESSION["id"])));
}
still an empty page. Then I tried:
public function isItSet($var)
{
die(isset($_SESSION));
}
This returns 1.
Can anyone tell me why trying to check if a session variable is set returns nothing?
To support isset() you need to overload the function in your wrapper.
So, in your wrapper, add:
public function __isset($var){
return isset($_SESSION[$var]);
}
To use it, you just have to do:
isset($this->session->myVar);
If it is still not working, do:
var_dump($_SESSION)
This will dump the whole $_SESSION array and show you whether the variable you are checking for actually exists.
In my opinion, issue is related to testing and not with PHP session.
The MAIN REASON behind why session variable isset returns nothing is use of
die()
function which is equivalent to exit() according to PHP manual itself.
http://in1.php.net/die
So, use var_dump() instead.
isset returns an empty page because your variable does not exist in session, so isset return false, however, echo false return ''.
It was already written in the commentary to hakre
You can test this like that:
echo "false : " . false . "\n";
echo "true : " . true . "\n";
=>
false :
true : 1
So, for your test, do a var_dump($_SESSION) and you will see if it is normal that isset($_SESSION['id']) returns false.
You can also test: die("false : " . (false == isset($_SESSION['id'])));
Your results are basically correct.
The boolean values being pass to each function just confused you i think.
Heres a clear explainations what happens to each of your statement.
LETS GET IT ONE BY ONE
// declaring this array as a set of session being passed as sample.
$string = array('name'=>'kaii');
echo die(isset($string['id'])); // figure 1
// step
// isset($string) returns a value of false because of unexistent of an array with the name of id.
// die(false) returns nothing because of the value being passed by isset is false.
// result would be definitely empty
echo die(is_null(isset($string['id']))); // figure 2
// step
// isset($string) returns a value of false because of unexistent of an array with the name of id.
// is_null(false) returns a value of false because it only accepts NULL as its parameter value to return true.
// die(false) returns nothing because of the value being passed by is_null is false.
// result would be definitely empty
echo die(isset($string)); //figure 3
// step
// isset($string) returns a value of true because of a $string variable is set and exist.
// die(true) returns a value of 1 because of the value being passed is true which is equivalent to 1 .
// result would be definitely return a value of 1.
note: In general your statement is correct just a few justification is needed to support it.
Additional:
print_r(),var_dump()
use it to check your session if it has a name that youre trying to
declared.
A brief explanation:
isset()
returns a boolean value of true or false
is_null()
accepts only a NULL parameter value to return a boolean value of
true else it goes false.
die()
returns a value of 1 for true and empty value for false.
Reasons:
A boolean TRUE value is converted to the string "1". Boolean
FALSE is converted to ""
The isset function: Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
if the session variable is set gives TRUE if the session variable unset it gives FALSE.
Example:
$_SESSION['views']=1; session variable is setted. => gives TRUE
unset($_SESSION['views']); session variable is not setted.
=> after this if(isset($_SESSION[$var])) it gives FALSE
There are two options: the session variable is setted or not.
isset() only works with variables as passing anything else will result in a parse error. For checking if constants are set use the defined() function.
For More Information about isset click here
A couple of things you could try:
Add this to your codebase: http://philsturgeon.co.uk/blog/2010/09/power-dump-php-applications. It's much better than var_dump and you can clearly see true or false for boolean values. It's saved me much grief.
Second, die() doesn't always give me what I expected, so it's better to echo something and then die() right after.
As #doydoy44 mentioned, false outputs a blank, so you might be getting a blank page for good reason. Again, the link above will solve this problem and make things clearer.
Your original code above has idUser as the variable being checked, all your other examples use id. I assume you know that, but I thought I'd mention it just in case.
Finally, I'd cross-check that the session wrapper was working as I'd expected, e.g.
if (!isset($this->session->idUser)) {
dump($_SESSION);
dump($this->session);
}
I'd obviously expect to get the same content back from both of them.
Hope that helps somewhat.
By the looks of it, it seems that there is no "ID" key on the session array.
This was verified on your comment to F21's answer ("undefined index error").
What you can do is define/initialize an "ID" key on the session array with value as null or empty string "" after your session has started. Then populate it with your value later on with your codes.
This is to make sure that when you use isset($_SESSION["ID"], the result can either be true or false rather than an undefined index error.
Session variables are a bit magic. Less magic than historically, but still it's unsurprising that unusual things are observed.
It would make sense to run the tests in the question in three states: once with the session variable set, and twice without the session variable set - once with a different session variable set and once with no session variables set.
Adapting F21's answer, to support isset() you need to overload the function in your wrapper. Whilst doing that you may as well create an isset that functions as you expect.
Something along the lines of the following will solve both the 'false is invisible' and an issue with removing session values.
public function __isset($var){
if (isset($_SESSION[$var]) && $_SESSION[$var]."">"") {
return true;
} else {
return false;
}
}
Related
I am just getting back in to PHP after many years and building a basic sit to start things off.
I have an index.php on my root and want to check for input from isset when either the value is ?home or just simply blank.
So easy enough I can start with:
if (isset($_GET['home']))
{
include $_SERVER['DOCUMENT_ROOT'] . '/content.html.php';
}
But my issue is trying to get it to work if there is nothing to get? I can see a couple of ways to do it but I think I am missing something simple to add to the first line.
Any help appreciated.
Lee
isset() checks if a variable has a value including ( False , 0 , or empty string) , but not NULL. Returns TRUE if variable exists otherwise returns FALSE.
On the other hand the empty() function checks if the variable has an empty value, empty string , 0, NULL ,or False. Returns FALSE if variable has a non-empty and non-zero value.
For details have a look here
http://us.php.net/manual/en/function.isset.php
http://us.php.net/manual/en/function.empty.php
Please help me understand the following codes:
<?php
session_start();
if(!isset($_SESSION['StaffId'])){
$_SESSION['StaffId']="";
}
?>
does it mean if there is not a set of StaffId, set it to null?
It's checking to see if the key 'StaffId' exists in the $_SESSION array.
For example, if you have an array:
$person = array( 'name' => 'george', 'age' => 22);
Then isset($person['name']) will return true but isset($person['height']) will return false.
So your code sample sets $_SESSION['StaffId'] to '' (an empty string), but only if that key has not been set yet for $_SESSION.
Edit: it's worth noting if you didn't know already that $_SESSION is a variable with special meaning in PHP, see the docs.
It simply checks to see if $_SESSION['StaffId'] is set.
If it is not then it sets it to "" which is an empty string not null
isset - Determine if a variable is set and is not NULL.
If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE if testing a variable that has been set to NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP NULL constant.
If multiple parameters are supplied then isset() will return TRUE only if all of the parameters are set. Evaluation goes from left to right and stops as soon as an unset variable is encountered.
Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
Here is my code:
<?php
$ja = '';
if(isset($ja))
echo "cool!";
?>
I get a "cool!" when running this simple piece of code in my browser. I learned from php.net that
isset — Determine if a variable is set
and is not NULL
Well, in my code, I did declare the variable $ja, but I didn't add any value to it, so shouldn't it be "NULL"?
Even though '' seems like nothing, it still has a value (a NULL character at the end of the string).
isset() checks if the variable is set or not, which in the case (to ''), it is. You may want to set $ja to NULL first beforehand, instead of setting it to an empty string... or use empty() ;)
The empty string is still a value. so you did give it a value which is not null - '' is a perfectly normal string value. perhaps you want ! empty($ja)
Isset is used to tell whether a variable is set or not:
isset($notDefined) //false
$notDefined = 0;
isset($notDefined) //true
(Assuming that $notDefined hasn't been defined before)
To check whether the variable is empty you can use if(empty($var)) or if($var==0)
You did add value to $ja - you set it to an empty string. An empty string is not null.
What you may be confused with is that an empty string and null both evaluate to "false" in PHP when you cast it to Boolean.
PHP's documentation is fairly clear on usage of isset.
The isset function does determine whether or not an object has a value. "NULL" is truly the only way to give an object a value of nothing. $s = '' simply gives an output of nothing. BOOL values(true/false) says that it's yes or no... 0 simply gives the object a int value of 0.
As the name implies of the function, it checks if some variable has been set, in a sense not that it has some value, but in a sense that it has been created. I think the name could be a bit confusing so I will bring a javascript analogy. In javascript to check if the variable exists you do the following:
if (typeof(somevar) == "undefined")
alert("Sorry, the variable has not been set already")
else
alert("Congratulations, the variable has not been set")
So, what you are doing is that you are making a variable $ja, and since by doing so, the variable already exists and therefore has been set.
Hope this helps
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
I am using the PHP in_array() function in order to authenticate (with sessions) if a user can access a particular page. For some reason, it is not working...
PHP PAGE
session_start();
require_once('../scripts/functions.php');
$role_auth = #$_SESSION['role_auth'];
access($role_auth, array(0,1,2,3,4));
access FUNCTION
function access($role_auth, $array){
if(!(in_array($role_auth, $array))){
header("Location: ../index.html");
}
}
If I insert print statements in the function, I can see that all of the correct values are being passed into the function. The problem is, if the function is called without a session variable set, for some reason it is considered as being in the array, and it authenticates.
Any ideas?
you may want to enable strict type checks by using:
in_array($role_auth, $array, true)
as what is likely happening is that $role_auth is being eval'd as false and that could match 0 in your in_array statement.
what you SHOULD be doing is this:
session_start();
require_once('../scripts/functions.php');
$role_auth = (isset($_SESSION['role_auth']))?$_SESSION['role_auth']:-1;
access($role_auth, array(0,1,2,3,4));
or something similiar. nothing good ever comes of using the # operator
I would check to see if $_SESSION['role_auth'] is actually set (with isset) instead of using # to suppress warnings (which is bad practice IMHO)
I think what's happening is that false == 0 ... so in_array returns true when nothing is in $role_auth because it sees it as 0 and 0 is in your array
$role_auth = #$_SESSION['role_auth'];
The # sign is suppressing any warnings you might get here, like index is not in array. How about something like this instead:
if(isset($_SESSION['role_auth']))
$role_auth = $_SESSION['role_auth'];
else
$role_auth = -1;//(or whatever an invalid role is)
In php, the number zero is considered equal to most non-numeric things, for example:
null == 0
false == 0
"" == 0
"asdf" == 0
You probably need to make sure that $_SESSION actually contains the 'role_auth' key beforehand and convert it to the appropriate type, also passing the $strict parameter to in_array, thus guaranteeing a type check as well as a value check (=== vs. ==). Removing zero from your array might also be a good idea.