Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Last active December 18, 2015 17:38
Show Gist options
  • Save CMCDragonkai/5819569 to your computer and use it in GitHub Desktop.
Save CMCDragonkai/5819569 to your computer and use it in GitHub Desktop.
PHP: Why PHP 5.4's session_status() is better than session_id() for determining if a PHP session is active. Also shows how to resolve multiple session restarting.
<?php
ob_start();
session_start();
var_dump(session_status());
var_dump(PHP_SESSION_ACTIVE);
var_dump(session_status() == PHP_SESSION_ACTIVE); //(true means active, false means no)
var_dump(session_id() !== '');
session_write_close();
var_dump(session_status());
var_dump(PHP_SESSION_ACTIVE);
var_dump(session_status() == PHP_SESSION_ACTIVE); //(true means active, false means no)
var_dump(session_id() !== '');
session_start();
session_regenerate_id(false);
// session_destroy();
//this will prevent multiple session cookies
if(defined('SID')){ //SID is the same as session_id(), they will always be true as long as you have used session_start() at least once in the script runtime
$headers = array_unique(headers_list());
$cookie_strings = array();
foreach($headers as $header){
if(preg_match('/^Set-Cookie: (.+)/', $header, $matches)){
$cookie_strings[] = $matches[1];
}
}
header_remove('Set-Cookie');
foreach($cookie_strings as $cookie){
header('Set-Cookie: ' . $cookie, false);
}
}
ob_flush();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment