Ceejay
Ceejay

Reputation: 7257

Check if session exists in php

In my php function here, i want to check if the session exists or not. based on the session existence i want to return true or false.

i have a login function which uses session_start(); and stores values into session variables when logged in, and when logged out it will do session_destroy();

now i want to check if the session exists or not. How can i do that

function ifsessionExists(){
    // check if session exists?
    if($_SESSION[] != ''){
    return true;
    }else{
    return false;
    }
}

Upvotes: 4

Views: 37228

Answers (6)

aldrin27
aldrin27

Reputation: 3407

Use isset function

function ifsessionExists(){
// check if session exists?
  if(isset($_SESSION)){
    return true;
  }else{
    return false;
  }
 }

You can also use empty function

 function ifsessionExists(){
// check if session exists?
  if(!empty($_SESSION)){
    return true;
  }else{
    return false;
  }
 }

Upvotes: 10

LIMEXS
LIMEXS

Reputation: 181

Try this:

function ifsessionExists(){
    // check if session exists?
    if(isset($_SESSION)){
    return true;
    }else{
    return false;
    }
}

Actualy, this is the better way to do this as suggested on session_status() documentation page:

<?php
/**
* @return bool
*/
function is_session_started()
{
    if ( php_sapi_name() !== 'cli' ) {
        if ( version_compare(phpversion(), '5.4.0', '>=') ) {
            return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
        } else {
            return session_id() === '' ? FALSE : TRUE;
        }
    }
    return FALSE;
}

// Example
if ( is_session_started() === FALSE ) session_start();
?>

Here you can read more about it https://www.php.net/manual/en/function.session-status.php#113468

Upvotes: 1

Sougata Bose
Sougata Bose

Reputation: 31739

You can use session_id().

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).

function ifsessionExists(){
    // check if session exists?
    $sid= session_id();
    return !empty($sid);
}

Upvotes: 2

Ajeet Kumar
Ajeet Kumar

Reputation: 815

Recommended way for versions of PHP >= 5.4.0

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

Source: http://www.php.net/manual/en/function.session-status.php

For versions of PHP < 5.4.0

if(session_id() == '') {
    session_start();
}

Upvotes: 7

Ninju
Ninju

Reputation: 2530

You can use isset

function ifsessionExists(){
    //check if session exists?
    if (isset($_SESSION['key'])){
    return true;
    }else{
    return false;
    }
}

Upvotes: 1

Harshit
Harshit

Reputation: 5157

Use

function ifsessionExists(){
// check if session exists?
if(isset($_SESSION['Key']) && $_SESSION['Key'] == 'Value'){
return true;
}else{
return false;
}
}

Upvotes: 2

Related Questions