Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load session_start() only if session does not exist?

Tags:

php

session

is there a short code trick to check if a session has started and if not then load one? Currently I receive an error "session already started..." if I put in a session start regardless of checking.

like image 644
acctman Avatar asked Apr 10 '12 17:04

acctman


People also ask

When should the session_start () function be used?

session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie. When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers.

How do you check if a session exists 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.

Which statement create a session if session does not exist?

You can use the session_status() function, a better option as it accounts for sessions being disabled and checks if a session already exists.


1 Answers

isset is generally the proper way to check if predefined variables are currently defined:

If you are using a version of php prior to 5.4,

you can usually get away with and its tempting just doing the code below, but be aware that if for some reason sessions are disabled, session_start() will still be called which could end up leading to errors and needless debugging since the $_SESSION array isn't allowed to be created.

if(!isset($_SESSION)){session_start();}

if you want to account for checking to see if sessions are disabled for some reason, you can supress the error message, set a test session variable, and then verify it was set. If its not, you can code in a reaction for disabled sessions. You'll want to do all this at or near the start of your script. So as an example(works differently depending on error handling setting):

if(!isset($_SESSION)){session_start();}
$_SESSION['valid'] = 'valid';
if($_SESSION['valid'] != 'valid')
{
   //handle disabled sessions
}

However, if you are using php version 5.4 or greater,

You can use the session_status() function, a better option as it accounts for sessions being disabled and checks if a session already exists.

if (session_status() === PHP_SESSION_NONE){session_start();}

NOTE that PHP_SESSION_NONE is a constant set by PHP and therefore does not need to be wrapped in quotes. It evaluates to integer 1, but as its a constant that was specifically set to eliminate the need for magic numbers, best to test against the constant.

like image 188
Rooster Avatar answered Sep 18 '22 19:09

Rooster