tags:

views:

1280

answers:

5

Is this bad practice?

if($_SESSION['something'] == '') {

    echo 'the session is empty';

}

Is there a way to check if a its empty or b it is not set? e.g something better than...

if(     $_SESSION['something'] == ''  ||    !isset($_SESSION['something'])   )  {

    echo 'the session is either empty or doesn't exist

}

OR does !isset just see if a $_SESSION exist and doesn't matter if there are values in the array?

Thanks for helping a newbie

+3  A: 

you are looking for PHP’s empty() function

knittl
empty is dangerous because it also reports false, 0 and "0" as empty.
OIS
+1  A: 

You could use the count() function to see how many entries there are in the $_SESSION array. This is not good practice. You should instead set the id of the user (or something similar) to check wheter the session was initialised or not.

if( !isset($_SESSION['uid']) )
    die( "Login required." );

(Assuming you want to check if someone is logged in)

svens
+6  A: 

I would use isset and empty:

session_start();
if(isset($_SESSION['blah']) && !empty($_SESSION['blah'])) {
   echo 'Set and not empty, and no undefined index error!');
}

array_key_exists is a nice alternative to using isset to check for keys:

session_start();
if(array_key_exists('blah',$_SESSION) && !empty($_SESSION['blah'])) {
    echo 'Set and not empty, and no undefined index error!');
}

Make sure you're calling session_start before reading from or writing to the session array.

karim79
no need to use isset if you are already using empty. empty will also check if the variable exists, i.e. is not null/undefined
knittl
No need to use isset AND empty.
Daok
@knittl It's good practice to actually make sure you have the variable before testing to see if it's empty.
random
@knittl - but then we don't know if it's been set or not, whether it's not set *or* empty true will be returned. I tend to use the above, but it might not always be needed.
karim79
Empty return false when not exist or null or "" or empty array. Why would you need to check if isset too? Read the help file : http://ca.php.net/empty
Daok
@Daok Variables can both exist and be blank. Checking to see if it exists AND is empty is a good idea.
random
usually you either want to check if the variable exists (`isset`) or if it contains any value evaluating to false (0, "0", null, false, …) (`empty`). `empty` will also return true on unset variables, so you don’t need `isset` first
knittl
+4  A: 

Use isset, empty or array_key_exists (especially for array keys) before accessing a variable whose existence you are not sure of. So change the order in your second example:

if (!isset($_SESSION['something']) || $_SESSION['something'] == '')
Gumbo
+2  A: 

If you want to check whether sessions are available, you probably want to use the session_id() function:

session_id() returns the session id for the current session or the empty string ("") if there is no current session (no current session id exists).
mjs