Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do check if a PHP session is empty?

Tags:

php

session

Is this bad practice?

if ($_SESSION['something'] == '') {     echo 'the session is empty'; } 

Is there a way to check if its empty or it is not set? I'm actualy doing this:

if (($_SESSION['something'] == '') || (!isset($_SESSION['something'])) {     echo 'the session is either empty or doesn\'t exist'; } 

Does !isset just checks if a $_SESSION[''] exist and doesn't check if, is there are values in the array or not

like image 730
willdanceforfun Avatar asked Oct 05 '09 12:10

willdanceforfun


People also ask

How do you check if PHP session is working?

You can check whether a variable has been set in a user's session using the function isset(), as you would a normal variable. Because the $_SESSION superglobal is only initialised once session_start() has been called, you need to call session_start() before using isset() on a session variable.

How check session is empty in laravel?

To determine if an item is present in the session, you may use the has method. The has method returns true if the item is present and is not null. To determine if an item is present in the session, even if its value is null, you may use the exists method.

How check session is present or not?

In ancient history you simply needed to check session_id() . If it's an empty string, then session is not started. Otherwise it is.


1 Answers

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.

like image 73
karim79 Avatar answered Sep 21 '22 22:09

karim79