3

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;
    }
}
CJAY
  • 6,055
  • 16
  • 52
  • 90

6 Answers6

7

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;
  }
 }
aldrin27
  • 3,341
  • 3
  • 22
  • 41
  • just doing `return isset($_Session);` or `return !empty($_Session);` does the same with less code (and shouldn't it be "not empty $_Session" in your example?) – wmk Sep 29 '15 at 07:13
5

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();
}
Ajeet Kumar
  • 791
  • 1
  • 5
  • 25
2

Use

function ifsessionExists(){
// check if session exists?
if(isset($_SESSION['Key']) && $_SESSION['Key'] == 'Value'){
return true;
}else{
return false;
}
}
Harshit
  • 4,929
  • 7
  • 36
  • 81
2

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);
}
Sougata Bose
  • 30,169
  • 8
  • 42
  • 82
1

You can use isset

function ifsessionExists(){
    //check if session exists?
    if (isset($_SESSION['key'])){
    return true;
    }else{
    return false;
    }
}
Ninju
  • 2,236
  • 2
  • 12
  • 20
1

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 http://sg2.php.net/manual/en/function.session-status.php#113468

LIMEXS
  • 181
  • 4