Detect if PHP session exists - php

Facebook now offer subscriptions to users so you can get realtime updates on changes. If my app receives an update, I plan to store it in the database. I would also like to detect if their session exists. If it does then I could update the data in there too.
My session IDs are MD5(fb_id + secret) so I could easily edit their session. The question is how can I detect if the session exists.

I use a combined version:
if(session_id() == '' || !isset($_SESSION) || session_status() === PHP_SESSION_NONE) {
// session isn't started
session_start();
}

If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used, use isset() to check a variable is registered in $_SESSION.
isset($_SESSION['varname'])

If you are on php 5.4+, it is cleaner to use session_status():
if (session_status() == PHP_SESSION_ACTIVE) {
echo 'Session is active';
}
PHP_SESSION_DISABLED if sessions are disabled.
PHP_SESSION_NONE if sessions are enabled, but none exists.
PHP_SESSION_ACTIVE if sessions are enabled, and one exists.

Which method is used to check if SESSION exists or not?
Answer:
isset($_SESSION['variable_name'])
Example:
isset($_SESSION['id'])

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();

The original code is from Sabry Suleiman.
Made it a bit prettier:
function is_session_started() {
if ( php_sapi_name() === 'cli' )
return false;
return version_compare( phpversion(), '5.4.0', '>=' )
? session_status() === PHP_SESSION_ACTIVE
: session_id() !== '';
}
First condition checks the Server API in use. If Command Line Interface is used, the function returns false.
Then we return the boolean result depending on the PHP version in use.
In ancient history you simply needed to check session_id(). If it's an empty string, then session is not started. Otherwise it is.
Since 5.4 to at least the current 8.0 the norm is to check session_status(). If it's not PHP_SESSION_ACTIVE, then either the session isn't started yet (PHP_SESSION_NONE) or sessions are not available altogether (PHP_SESSION_DISABLED).

Shortest and simple answer
$_SESSION['variable_name']?? die;
its a simple way doing
if(isset($_session['variable'])){
// do something
}else{
die;
}

Related

I have an error when I try to use a session from my login file in another file [duplicate]

I have a PHP file that is sometimes called from a page that has started a session and sometimes from a page that doesn't have session started. Therefore when I have session_start() on this script I sometimes get the error message for "session already started". For that I've put these lines:
if(!isset($_COOKIE["PHPSESSID"]))
{
session_start();
}
but this time I got this warning message:
Notice: Undefined variable: _SESSION
Is there a better way to check if session has already started?
If I use #session_start will it make things work properly and just shut up the warnings?
Recommended way for versions of PHP >= 5.4.0 , PHP 7, PHP 8
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
Reference: http://www.php.net/manual/en/function.session-status.php
For versions of PHP < 5.4.0
if(session_id() == '') {
session_start();
}
For versions of PHP prior to PHP 5.4.0:
if(session_id() == '') {
// session isn't started
}
Though, IMHO, you should really think about refactoring your session management code if you don't know whether or not a session is started...
That said, my opinion is subjective, and there are situations (examples of which are described in the comments below) where it may not be possible to know if the session is started.
PHP 5.4 introduced session_status(), which is more reliable than relying on session_id().
Consider the following snippet:
session_id('test');
var_export(session_id() != ''); // true, but session is still not started!
var_export(session_status() == PHP_SESSION_ACTIVE); // false
So, to check whether a session is started, the recommended way in PHP 5.4 is now:
session_status() == PHP_SESSION_ACTIVE
you can do this, and it's really easy.
if (!isset($_SESSION)) session_start();
if (version_compare(phpversion(), '5.4.0', '<')) {
if(session_id() == '') {
session_start();
}
}
else
{
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
}
Prior to PHP 5.4 there is no reliable way of knowing other than setting a global flag.
Consider:
var_dump($_SESSION); // null
session_start();
var_dump($_SESSION); // array
session_destroy();
var_dump($_SESSION); // array, but session isn't active.
Or:
session_id(); // returns empty string
session_start();
session_id(); // returns session hash
session_destroy();
session_id(); // returns empty string, ok, but then
session_id('foo'); // tell php the session id to use
session_id(); // returns 'foo', but no session is active.
So, prior to PHP 5.4 you should set a global boolean.
For all php version
if ((function_exists('session_status')
&& session_status() !== PHP_SESSION_ACTIVE) || !session_id()) {
session_start();
}
Check this :
<?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();
?>
Source http://php.net
Use session_id(), it returns an empty string if not set. It's more reliable than checking the $_COOKIE.
if (strlen(session_id()) < 1) {
session_start();
}
if (session_id() === "") { session_start(); }
hope it helps !
This should work for all PHP versions. It determines the PHP version, then checks to see if the session is started based on the PHP version. Then if the session is not started it starts it.
function start_session() {
if(version_compare(phpversion(), "5.4.0") != -1){
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
} else {
if(session_id() == '') {
session_start();
}
}
}
The only thing you need to do is:
<?php
if(!isset($_SESSION))
{
session_start();
}
?>
Not sure about efficiency of such solution, but this is from working project
This is also used if you need to define the default language
/**
* Start session
* Fall back to ukrainian language
*/
function valid_session() {
if(session_id()=='') {
session_start();
$_SESSION['lang']='uk';
$_SESSION['lang_id']=3;
}
return true;
}
# before a function call suppresses any errors that may be reported during the function call.
Adding a # before session_start tells PHP to avoid printing error messages.
For example:
Using session_start() after you've already printed something to the browser results in an error so PHP will display something like "headers cannot be sent: started at (line 12)", #session_start() will still fail in this case, but the error message is not printed on screen.
Before including the files or redirecting to new page use the exit() function, otherwise it will give an error.
This code can be used in all cases:
<?php
if (session_status() !== PHP_SESSION_ACTIVE || session_id() === ""){
session_start();
}
?>
On PHP 5.3 this works for me:
if(!strlen(session_id())){
session_name('someSpecialName');
session_start();
}
then you have. If you do not put the not at if statement beginning the session will start any way I do not why.
Response BASED on #Meliza Ramos Response(see first response) and http://php.net/manual/en/function.phpversion.php ,
ACTIONS:
define PHP_VERSION_ID if not exist
define function to check version based on PHP_VERSION_ID
define function to openSession() secure
only use openSession()
// PHP_VERSION_ID is available as of PHP 5.2.7, if our
// version is lower than that, then emulate it
if (!defined('PHP_VERSION_ID')) {
$version = explode('.', PHP_VERSION);
define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
// PHP_VERSION_ID is defined as a number, where the higher the number
// is, the newer a PHP version is used. It's defined as used in the above
// expression:
//
// $version_id = $major_version * 10000 + $minor_version * 100 + $release_version;
//
// Now with PHP_VERSION_ID we can check for features this PHP version
// may have, this doesn't require to use version_compare() everytime
// you check if the current PHP version may not support a feature.
//
// For example, we may here define the PHP_VERSION_* constants thats
// not available in versions prior to 5.2.7
if (PHP_VERSION_ID < 50207) {
define('PHP_MAJOR_VERSION', $version[0]);
define('PHP_MINOR_VERSION', $version[1]);
define('PHP_RELEASE_VERSION', $version[2]);
// and so on, ...
}
}
function phpVersionAtLeast($strVersion = '0.0.0')
{
$version = explode('.', $strVersion);
$questionVer = $version[0] * 10000 + $version[1] * 100 + $version[2];
if(PHP_VERSION_ID >= $questionVer)
return true;
else
return false;
}
function openSession()
{
if(phpVersionAtLeast('5.4.0'))
{
if(session_status()==PHP_SESSION_NONE)
session_start();
}
else // under 5.4.0
{
if(session_id() == '')
session_start();
}
}
if (version_compare(PHP_VERSION, "5.4.0") >= 0) {
$sess = session_status();
if ($sess == PHP_SESSION_NONE) {
session_start();
}
} else {
if (!$_SESSION) {
session_start();
}
}
Actually, it is now too late to explain it here anyway as its been solved.
This was a .inc file of one of my projects where you configure a menu for a restaurant by selecting a dish and remove/add or change the order.
The server I was working at did not had the actual version so I made it more flexible. It's up to the authors wish to use and try it out.
Is this code snippet work for you?
if (!count($_SESSION)>0) {
session_start();
}
This is what I use to determine if a session has started. By using empty and isset as follows:
if (empty($_SESSION) && !isset($_SESSION)) {
session_start();
}
You should reorganize your code so that you call session_start() exactly once per page execution.
PHP_VERSION_ID is available as of PHP 5.2.7, so check this first and if necessary , create it.
session_status is available as of PHP 5.4 , so we have to check this too:
if (!defined('PHP_VERSION_ID')) {
$version = explode('.', PHP_VERSION);
define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
}else{
$version = PHP_VERSION_ID;
}
if($version < 50400){
if(session_id() == '') {
session_start();
}
}else{
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
}
Based on my practice, before accessing the $_SESSION[] you need to call session_start every time to use the script. See the link below for manual.
http://php.net/manual/en/function.session-start.php
For me at least session_start is confusing as a name. A session_load can be more clear.
i ended up with double check of status. php 5.4+
if(session_status() !== PHP_SESSION_ACTIVE){session_start();};
if(session_status() !== PHP_SESSION_ACTIVE){die('session start failed');};
You can use the following solution to check if a PHP session has already started:
if(session_id()== '')
{
echo"Session isn't Start";
}
else
{
echo"Session Started";
}
The absolute simplest way:
(session_status()==2)?:session_start();
session_start();
if(!empty($_SESSION['user']))
{
//code;
}
else
{
header("location:index.php");
}
Replace session_start(); with:
if (!isset($a)) {
a = False;
if ($a == TRUE) {
session_start();
$a = TRUE;
}
}

After switching from file to session vars the functions don't work

I have two methods which work without problems
public static function appendGamer($gamer) {
file_put_contents(self::$fileName, $gamer, FILE_APPEND);
}
and
private function selectLastGamer() {
$gamers = file(self::$fileName);
if (sizeof($gamers) > self::$totalGamers) {
self::$totalGamers = sizeof($gamers);
return trim($gamers[self::$totalGamers - 1]);
}
return "";
}
Now I want everything to be stored in session vars rather than traditional text files. So i rewrite these functions the following way
public static function appendGamer($gamer) {
$old = trim($_SESSION["gamers"]);
$_SESSION["gamers"] = ($old == "") ? $gamer : $old . PHP_EOL . $gamer;
}
and
private function selectLastGamer() {
$gamers = explode(PHP_EOL, $_SESSION["gamers"]);
if (sizeof($gamers) > self::$totalGamers) {
self::$totalGamers = sizeof($gamers);
return trim($gamers[self::$totalGamers - 1]);
}
return "";
}
But now these functions don't work. I mean now selectLastGamer always returns empty string. The session variable is automatically created in constructor so it is always set. What's wrong with new version of these functions?
You should start session on every page like
if( session_status() != PHP_SESSION_DISABLED )
{
session_start();
}
OR
if( session_status() == PHP_SESSION_NONE || session_status() == PHP_SESSION_ACTIVE)
{
session_start();
}
Because session_status() returns any one of the following value at a time.
PHP_SESSION_DISABLED if sessions are disabled.
PHP_SESSION_NONE if sessions are enabled, but none exists.
PHP_SESSION_ACTIVE if sessions are enabled, and one exists.
Hope it ll work for you.
Start session on every page you want to access the session variable set/get using session_start(); at the top of the page.
On main page and also on the page where functions are defined.

PHP $_SESSION variables are not being passed between pages

I am working on a school project where I need my .php pages communicating. I have header.php where I set connection to the database and start the session. In order to start the session only once, I've used this:
if(session_id() == '') {
session_start();
}
PHP version is PHP 5.3.10-1 ubuntu3.18 with Suhosin-Patch (cli)
I am trying to pass some $_SESSION variables between pages, but they keep being unset when I try to use them on a page that doesn't set them.
I see many people have complained about this, but I still can't find the solution.
login-form.php
<?php
if (isset($_SESSION["login-error"])) {
echo '<p>'.$_SESSION["login-error"].'</p>';
}
?>
login.php
$_SESSION["login-error"]= "Username or password incorrect";
There is a code snippet of what is not working for me.
Thanks
You can try this.
In your function file put this
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;
}
Then you can run this in every page you want session started
if ( is_session_started() === FALSE ) session_start();
With this I think you should be good to go on starting your session across pages. Next is to ensure you set a session to a value. If you are not sure what is unsetting your sessions you can try var_dump($_SESSION) at different parts of your code so you be sure at what point it resets then know how to deal with it.
The variables are probable not set, because you haven't activate the session variables with session_start().
session_id() == '' is not a correct conditional . Use instead:
if (!isset($_SESSION)) { session_start();}
if you have session started then you can set a session variable
if (!isset($_SESSION["login-error"])) { $_SESSION["login-error"]= "Username or password incorrect";}
Before you call $_SESSION["login-error"], type session_start(), just for testing, to find when the session signal is missing. You said
PHP $_SESSION variables are not being passed between pages
session_start() and SESSION variables needs to be included at the beginning of EVERY page or at the place where SESSION variables are being called (through a common file, bootstrap, config or sth) at the beginning of EVERY page. ie the command to read those data from the server is needed.
Since my header.php file included "connection.php" file, I put
session_start();
at the beginning of connection.php and deleted it from header.php file. Now it works fine. Thanks all for your help!
PHP sessions rely on components of HTTP, like Cookies and GET variables, which are clearly not available when you're calling a script via the CLI. You could try faking entries in the PHP superglobals, but that is wholly inadvisable. Instead, implement a basic cache yourself.
<?php
class MyCache implements ArrayAccess {
protected $cacheDir, $cacheKey, $cacheFile, $cache;
public function __construct($cacheDir, $cacheKey) {
if( ! is_dir($cacheDir) ) { throw new Exception('Cache directory does not exist: '.$cacheDir); }
$this->cacheDir = $cacheDir;
$this->cacheKey = $cacheKey;
$this->cacheFile = $this->cacheDir . md5($this->cacheKey) . '.cache';
// get the cache if there already is one
if( file_exists($this->cacheFile) ) {
$this->cache = unserialize(file_get_contents($this->cacheFile));
} else {
$this->cache = [];
}
}
// save the cache when the object is destructed
public function __destruct() {
file_put_contents($this->cacheFile, serialize($this->cache));
}
// ArrayAccess functions
public function offsetExists($offset) { return isset($this->cache[$offset]); }
public function offsetGet($offset) { return $this->cache[$offset]; }
public function offsetSet($offset, $value) { $this->cache[$offset] = $value; }
public function offsetUnset($offset) { unset($this->cache[$offset]); }
}
$username = exec('whoami');
$c = new MyCache('./cache/', $username);
if( isset($c['foo']) ) {
printf("Foo is: %s\n", $c['foo']);
} else {
$c['foo'] = md5(rand());
printf("Set Foo to %s", $c['foo']);
}
Example runs:
# php cache.php
Set Foo to e4be2bd956fd81f3c78b621c2f4bed47
# php cache.php
Foo is: e4be2bd956fd81f3c78b621c2f4bed47
This is pretty much all PHP's sessions do, except a random cache key is generated [aka PHPSESSID] and is set as a cookie, and the cache directory is session.save_path from php.ini.

Suppress FastCGI PHP's session_start error in webserver logs when continuing session [duplicate]

I have a PHP file that is sometimes called from a page that has started a session and sometimes from a page that doesn't have session started. Therefore when I have session_start() on this script I sometimes get the error message for "session already started". For that I've put these lines:
if(!isset($_COOKIE["PHPSESSID"]))
{
session_start();
}
but this time I got this warning message:
Notice: Undefined variable: _SESSION
Is there a better way to check if session has already started?
If I use #session_start will it make things work properly and just shut up the warnings?
Recommended way for versions of PHP >= 5.4.0 , PHP 7, PHP 8
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
Reference: http://www.php.net/manual/en/function.session-status.php
For versions of PHP < 5.4.0
if(session_id() == '') {
session_start();
}
For versions of PHP prior to PHP 5.4.0:
if(session_id() == '') {
// session isn't started
}
Though, IMHO, you should really think about refactoring your session management code if you don't know whether or not a session is started...
That said, my opinion is subjective, and there are situations (examples of which are described in the comments below) where it may not be possible to know if the session is started.
PHP 5.4 introduced session_status(), which is more reliable than relying on session_id().
Consider the following snippet:
session_id('test');
var_export(session_id() != ''); // true, but session is still not started!
var_export(session_status() == PHP_SESSION_ACTIVE); // false
So, to check whether a session is started, the recommended way in PHP 5.4 is now:
session_status() == PHP_SESSION_ACTIVE
you can do this, and it's really easy.
if (!isset($_SESSION)) session_start();
if (version_compare(phpversion(), '5.4.0', '<')) {
if(session_id() == '') {
session_start();
}
}
else
{
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
}
Prior to PHP 5.4 there is no reliable way of knowing other than setting a global flag.
Consider:
var_dump($_SESSION); // null
session_start();
var_dump($_SESSION); // array
session_destroy();
var_dump($_SESSION); // array, but session isn't active.
Or:
session_id(); // returns empty string
session_start();
session_id(); // returns session hash
session_destroy();
session_id(); // returns empty string, ok, but then
session_id('foo'); // tell php the session id to use
session_id(); // returns 'foo', but no session is active.
So, prior to PHP 5.4 you should set a global boolean.
For all php version
if ((function_exists('session_status')
&& session_status() !== PHP_SESSION_ACTIVE) || !session_id()) {
session_start();
}
Check this :
<?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();
?>
Source http://php.net
Use session_id(), it returns an empty string if not set. It's more reliable than checking the $_COOKIE.
if (strlen(session_id()) < 1) {
session_start();
}
if (session_id() === "") { session_start(); }
hope it helps !
This should work for all PHP versions. It determines the PHP version, then checks to see if the session is started based on the PHP version. Then if the session is not started it starts it.
function start_session() {
if(version_compare(phpversion(), "5.4.0") != -1){
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
} else {
if(session_id() == '') {
session_start();
}
}
}
The only thing you need to do is:
<?php
if(!isset($_SESSION))
{
session_start();
}
?>
Not sure about efficiency of such solution, but this is from working project
This is also used if you need to define the default language
/**
* Start session
* Fall back to ukrainian language
*/
function valid_session() {
if(session_id()=='') {
session_start();
$_SESSION['lang']='uk';
$_SESSION['lang_id']=3;
}
return true;
}
# before a function call suppresses any errors that may be reported during the function call.
Adding a # before session_start tells PHP to avoid printing error messages.
For example:
Using session_start() after you've already printed something to the browser results in an error so PHP will display something like "headers cannot be sent: started at (line 12)", #session_start() will still fail in this case, but the error message is not printed on screen.
Before including the files or redirecting to new page use the exit() function, otherwise it will give an error.
This code can be used in all cases:
<?php
if (session_status() !== PHP_SESSION_ACTIVE || session_id() === ""){
session_start();
}
?>
On PHP 5.3 this works for me:
if(!strlen(session_id())){
session_name('someSpecialName');
session_start();
}
then you have. If you do not put the not at if statement beginning the session will start any way I do not why.
Response BASED on #Meliza Ramos Response(see first response) and http://php.net/manual/en/function.phpversion.php ,
ACTIONS:
define PHP_VERSION_ID if not exist
define function to check version based on PHP_VERSION_ID
define function to openSession() secure
only use openSession()
// PHP_VERSION_ID is available as of PHP 5.2.7, if our
// version is lower than that, then emulate it
if (!defined('PHP_VERSION_ID')) {
$version = explode('.', PHP_VERSION);
define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
// PHP_VERSION_ID is defined as a number, where the higher the number
// is, the newer a PHP version is used. It's defined as used in the above
// expression:
//
// $version_id = $major_version * 10000 + $minor_version * 100 + $release_version;
//
// Now with PHP_VERSION_ID we can check for features this PHP version
// may have, this doesn't require to use version_compare() everytime
// you check if the current PHP version may not support a feature.
//
// For example, we may here define the PHP_VERSION_* constants thats
// not available in versions prior to 5.2.7
if (PHP_VERSION_ID < 50207) {
define('PHP_MAJOR_VERSION', $version[0]);
define('PHP_MINOR_VERSION', $version[1]);
define('PHP_RELEASE_VERSION', $version[2]);
// and so on, ...
}
}
function phpVersionAtLeast($strVersion = '0.0.0')
{
$version = explode('.', $strVersion);
$questionVer = $version[0] * 10000 + $version[1] * 100 + $version[2];
if(PHP_VERSION_ID >= $questionVer)
return true;
else
return false;
}
function openSession()
{
if(phpVersionAtLeast('5.4.0'))
{
if(session_status()==PHP_SESSION_NONE)
session_start();
}
else // under 5.4.0
{
if(session_id() == '')
session_start();
}
}
if (version_compare(PHP_VERSION, "5.4.0") >= 0) {
$sess = session_status();
if ($sess == PHP_SESSION_NONE) {
session_start();
}
} else {
if (!$_SESSION) {
session_start();
}
}
Actually, it is now too late to explain it here anyway as its been solved.
This was a .inc file of one of my projects where you configure a menu for a restaurant by selecting a dish and remove/add or change the order.
The server I was working at did not had the actual version so I made it more flexible. It's up to the authors wish to use and try it out.
Is this code snippet work for you?
if (!count($_SESSION)>0) {
session_start();
}
This is what I use to determine if a session has started. By using empty and isset as follows:
if (empty($_SESSION) && !isset($_SESSION)) {
session_start();
}
You should reorganize your code so that you call session_start() exactly once per page execution.
PHP_VERSION_ID is available as of PHP 5.2.7, so check this first and if necessary , create it.
session_status is available as of PHP 5.4 , so we have to check this too:
if (!defined('PHP_VERSION_ID')) {
$version = explode('.', PHP_VERSION);
define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
}else{
$version = PHP_VERSION_ID;
}
if($version < 50400){
if(session_id() == '') {
session_start();
}
}else{
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
}
Based on my practice, before accessing the $_SESSION[] you need to call session_start every time to use the script. See the link below for manual.
http://php.net/manual/en/function.session-start.php
For me at least session_start is confusing as a name. A session_load can be more clear.
i ended up with double check of status. php 5.4+
if(session_status() !== PHP_SESSION_ACTIVE){session_start();};
if(session_status() !== PHP_SESSION_ACTIVE){die('session start failed');};
You can use the following solution to check if a PHP session has already started:
if(session_id()== '')
{
echo"Session isn't Start";
}
else
{
echo"Session Started";
}
The absolute simplest way:
(session_status()==2)?:session_start();
session_start();
if(!empty($_SESSION['user']))
{
//code;
}
else
{
header("location:index.php");
}
Replace session_start(); with:
if (!isset($a)) {
a = False;
if ($a == TRUE) {
session_start();
$a = TRUE;
}
}

Check if PHP session has already started

I have a PHP file that is sometimes called from a page that has started a session and sometimes from a page that doesn't have session started. Therefore when I have session_start() on this script I sometimes get the error message for "session already started". For that I've put these lines:
if(!isset($_COOKIE["PHPSESSID"]))
{
session_start();
}
but this time I got this warning message:
Notice: Undefined variable: _SESSION
Is there a better way to check if session has already started?
If I use #session_start will it make things work properly and just shut up the warnings?
Recommended way for versions of PHP >= 5.4.0 , PHP 7, PHP 8
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
Reference: http://www.php.net/manual/en/function.session-status.php
For versions of PHP < 5.4.0
if(session_id() == '') {
session_start();
}
For versions of PHP prior to PHP 5.4.0:
if(session_id() == '') {
// session isn't started
}
Though, IMHO, you should really think about refactoring your session management code if you don't know whether or not a session is started...
That said, my opinion is subjective, and there are situations (examples of which are described in the comments below) where it may not be possible to know if the session is started.
PHP 5.4 introduced session_status(), which is more reliable than relying on session_id().
Consider the following snippet:
session_id('test');
var_export(session_id() != ''); // true, but session is still not started!
var_export(session_status() == PHP_SESSION_ACTIVE); // false
So, to check whether a session is started, the recommended way in PHP 5.4 is now:
session_status() == PHP_SESSION_ACTIVE
you can do this, and it's really easy.
if (!isset($_SESSION)) session_start();
if (version_compare(phpversion(), '5.4.0', '<')) {
if(session_id() == '') {
session_start();
}
}
else
{
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
}
Prior to PHP 5.4 there is no reliable way of knowing other than setting a global flag.
Consider:
var_dump($_SESSION); // null
session_start();
var_dump($_SESSION); // array
session_destroy();
var_dump($_SESSION); // array, but session isn't active.
Or:
session_id(); // returns empty string
session_start();
session_id(); // returns session hash
session_destroy();
session_id(); // returns empty string, ok, but then
session_id('foo'); // tell php the session id to use
session_id(); // returns 'foo', but no session is active.
So, prior to PHP 5.4 you should set a global boolean.
For all php version
if ((function_exists('session_status')
&& session_status() !== PHP_SESSION_ACTIVE) || !session_id()) {
session_start();
}
Check this :
<?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();
?>
Source http://php.net
Use session_id(), it returns an empty string if not set. It's more reliable than checking the $_COOKIE.
if (strlen(session_id()) < 1) {
session_start();
}
if (session_id() === "") { session_start(); }
hope it helps !
This should work for all PHP versions. It determines the PHP version, then checks to see if the session is started based on the PHP version. Then if the session is not started it starts it.
function start_session() {
if(version_compare(phpversion(), "5.4.0") != -1){
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
} else {
if(session_id() == '') {
session_start();
}
}
}
The only thing you need to do is:
<?php
if(!isset($_SESSION))
{
session_start();
}
?>
Not sure about efficiency of such solution, but this is from working project
This is also used if you need to define the default language
/**
* Start session
* Fall back to ukrainian language
*/
function valid_session() {
if(session_id()=='') {
session_start();
$_SESSION['lang']='uk';
$_SESSION['lang_id']=3;
}
return true;
}
# before a function call suppresses any errors that may be reported during the function call.
Adding a # before session_start tells PHP to avoid printing error messages.
For example:
Using session_start() after you've already printed something to the browser results in an error so PHP will display something like "headers cannot be sent: started at (line 12)", #session_start() will still fail in this case, but the error message is not printed on screen.
Before including the files or redirecting to new page use the exit() function, otherwise it will give an error.
This code can be used in all cases:
<?php
if (session_status() !== PHP_SESSION_ACTIVE || session_id() === ""){
session_start();
}
?>
On PHP 5.3 this works for me:
if(!strlen(session_id())){
session_name('someSpecialName');
session_start();
}
then you have. If you do not put the not at if statement beginning the session will start any way I do not why.
Response BASED on #Meliza Ramos Response(see first response) and http://php.net/manual/en/function.phpversion.php ,
ACTIONS:
define PHP_VERSION_ID if not exist
define function to check version based on PHP_VERSION_ID
define function to openSession() secure
only use openSession()
// PHP_VERSION_ID is available as of PHP 5.2.7, if our
// version is lower than that, then emulate it
if (!defined('PHP_VERSION_ID')) {
$version = explode('.', PHP_VERSION);
define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
// PHP_VERSION_ID is defined as a number, where the higher the number
// is, the newer a PHP version is used. It's defined as used in the above
// expression:
//
// $version_id = $major_version * 10000 + $minor_version * 100 + $release_version;
//
// Now with PHP_VERSION_ID we can check for features this PHP version
// may have, this doesn't require to use version_compare() everytime
// you check if the current PHP version may not support a feature.
//
// For example, we may here define the PHP_VERSION_* constants thats
// not available in versions prior to 5.2.7
if (PHP_VERSION_ID < 50207) {
define('PHP_MAJOR_VERSION', $version[0]);
define('PHP_MINOR_VERSION', $version[1]);
define('PHP_RELEASE_VERSION', $version[2]);
// and so on, ...
}
}
function phpVersionAtLeast($strVersion = '0.0.0')
{
$version = explode('.', $strVersion);
$questionVer = $version[0] * 10000 + $version[1] * 100 + $version[2];
if(PHP_VERSION_ID >= $questionVer)
return true;
else
return false;
}
function openSession()
{
if(phpVersionAtLeast('5.4.0'))
{
if(session_status()==PHP_SESSION_NONE)
session_start();
}
else // under 5.4.0
{
if(session_id() == '')
session_start();
}
}
if (version_compare(PHP_VERSION, "5.4.0") >= 0) {
$sess = session_status();
if ($sess == PHP_SESSION_NONE) {
session_start();
}
} else {
if (!$_SESSION) {
session_start();
}
}
Actually, it is now too late to explain it here anyway as its been solved.
This was a .inc file of one of my projects where you configure a menu for a restaurant by selecting a dish and remove/add or change the order.
The server I was working at did not had the actual version so I made it more flexible. It's up to the authors wish to use and try it out.
Is this code snippet work for you?
if (!count($_SESSION)>0) {
session_start();
}
This is what I use to determine if a session has started. By using empty and isset as follows:
if (empty($_SESSION) && !isset($_SESSION)) {
session_start();
}
You should reorganize your code so that you call session_start() exactly once per page execution.
PHP_VERSION_ID is available as of PHP 5.2.7, so check this first and if necessary , create it.
session_status is available as of PHP 5.4 , so we have to check this too:
if (!defined('PHP_VERSION_ID')) {
$version = explode('.', PHP_VERSION);
define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
}else{
$version = PHP_VERSION_ID;
}
if($version < 50400){
if(session_id() == '') {
session_start();
}
}else{
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
}
Based on my practice, before accessing the $_SESSION[] you need to call session_start every time to use the script. See the link below for manual.
http://php.net/manual/en/function.session-start.php
For me at least session_start is confusing as a name. A session_load can be more clear.
i ended up with double check of status. php 5.4+
if(session_status() !== PHP_SESSION_ACTIVE){session_start();};
if(session_status() !== PHP_SESSION_ACTIVE){die('session start failed');};
You can use the following solution to check if a PHP session has already started:
if(session_id()== '')
{
echo"Session isn't Start";
}
else
{
echo"Session Started";
}
The absolute simplest way:
(session_status()==2)?:session_start();
session_start();
if(!empty($_SESSION['user']))
{
//code;
}
else
{
header("location:index.php");
}
Replace session_start(); with:
if (!isset($a)) {
a = False;
if ($a == TRUE) {
session_start();
$a = TRUE;
}
}

Categories