Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if session is set or not, and if not create one?

Tags:

php

session

I want to check if a session is currently set, and if so do allow the page to run as normal (do nothing) if not create a session.

I had a look at another SO question, in which the following code was posted:

if ( empty( $_SESSION['login'] )) { } else { }

Would the easiest way to do this be to set something like $_SESSION['a'] for each session, and then run if(empty($_SESSION['a'])) to check if a session exists?

Then again, can you use a session variable without invoking session_start() in the first place, thus making it obsolete (I tried this yesterday, as an echo though, not an if statement to check that a variable was carrying through without realizing that session_start() needed to be invoked before I could echo the variable).

There's probably an easy way that's oft used, I just can't seem to find it.

Any help would be greatly appreciated!

like image 996
Fireworksable Avatar asked Aug 01 '11 16:08

Fireworksable


1 Answers

session_id() returns the string identifying the current session. If a session hasn't been initialized, it will return an empty string.

 if(session_id())
 {
      // session has been started
 }
 else
 {
      // session has NOT been started
      session_start();
 }
like image 65
Chris Hepner Avatar answered Oct 07 '22 17:10

Chris Hepner