In this tutorial we will see How To Check If Session Is Started in PHP. PHP session_status() Function and PHP session_id() Function can be used to check if session is already started or not.
Table of Contents
PHP session_status() Function
PHP session_status() Function returns the current status of session. It is used to check the session.
In this example session_status() Function is used to check if session is started or not.
Note: This is ideal for PHP 5.4.0 or higher.
<?php
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
?>
In above code PHP_SESSION_NONE is a value which is returned by session_status() function, if session is enabled but it doesn't exists or it hasn't been started yet.
PHP session_id() Function
PHP session_id() Function sets or returns the id of the current session.
In second example, session_id() Function is used to check the id of session, this can tell if the session has been started or not.
Note: This works with PHP 5.4.0 or lower.
<?php
if(session_id() == ''){
session_start();
}
?>
Another possible way to check the session, is by using this code.
<?php
if (!isset($_SESSION))
{
session_start();
}
?>
In this third example isset() function is used which checks whether a variable is set or not.
Session is started with the session_start() function.