Codeigniter & PHP check if session exist

24,331

Solution 1

Check for a valid session id:

$sid = session_id();

For example:

$sid = session_id();
if($sid) {
    echo "Session exists!";
} else {
    session_start();
}

Solution 2

The first point is "Don't fight the framework" when your framework has some functions than use it. Normally in the Framework classes are functions to prevent injections.

Here is a Post when tells you how to check the cookie:

Check if cookies are enabled

And for the session

How to tell if a session is active?

Solution 3

I think you can simply check by doing something like:

if(isset($_SESSION)){
  // tells php session is initiated
}
if(isset($_COOKIE)){

}
Share:
24,331
itsme
Author by

itsme

JS

Updated on July 09, 2022

Comments

  • itsme
    itsme almost 2 years

    How can i simply check if cookies are enabled and user session too in PHP?

    I need the really lighter piece of code of this world to do that, can anyone show me somenthing?

    I'm on Codeigniter but i'm planning to use native PHP for this control.

    my code:

    if(session_start()){ echo 'started'; }
    

    as i know Codeigniter doesn't uses native PHP session, how to do so?

  • Brendan Bullen
    Brendan Bullen over 11 years
    No, if no session id exists, it just means that no session has been started. Not that it can't be started.
  • itsme
    itsme over 11 years
    codeigniter i think it's not using native PHP session, i'm in trouble with this