Addendum to Ensuring Unique ession ID
Steps
- Create tables
DROP TABLE IF EXISTS `sessions_with_db`; CREATE TABLE IF NOT EXISTS `sessions_with_db` ( `id` varchar(32) COLLATE utf8_unicode_ci NOT NULL, `access` datetime NOT NULL, `data` text COLLATE utf8_unicode_ci NOT NULL, `cookie_start_time` datetime NOT NULL DEFAULT '1970-01-01 00:00:00', UNIQUE KEY `id` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
- Include DBSessionHandler Class(SessionHandlerHelper)
- // Set handler to overide SESSION
session_set_save_handler(
array($this, "_open"),
array($this, "_close"),
array($this, "_read"),
array($this, "_write"),
array($this, "_destroy"),
array($this, "_gc")
); register_shutdown_function('session_write_close');
These codes are mandatory for DB Session Handling.
-
Set Session Start time as current time
$this->cookieStartTime = now();
3.
if(!isset($_COOKIE['cookie_start_time'])) { setcookie($cookie_name, $cookie_value, time() + $this->cookieLifeTime /* (86400 * 30) */, "/"); // 86400 = 1 day } else { $this->cookieStartTime = $_COOKIE['cookie_start_time']; }//if(!isset($_COOKIE['cookie_start_time']))
4.
setcookie($cookie_name/*cookie_start_time */, $cookie_value/*$this->cookieStartTime*/, time() + $this->cookieLifeTime /* (86400 * 30) */, "/"); // 86400 = 1 day
5.
session_start([//https://www.php.net/manual/en/function.session-start.php#example-5976
//'cookie_lifetime' => 86400,//60 * 60 * 24 * 7 // 7 day cookie lifetime
'cookie_lifetime' => $this->sessionSettings['session_life_time'],//31536000,//60 * 60 * 24 *365 -> 365 day cookie lifetime
]);
-
in session '_write' we will set that value to db table field cookie_start_time same as $this->cookieStartTime
-
in session '_read' we do a check
if($getRowsOfSession[0]['cookie_start_time'] != $this->cookieStartTime)
-
if it returns true, that means this is a
duplicate session
and the user is redirected to destroy the session and again redirected to start a new session.(2 redirections total) -
Now , check for duplicate session as the first line before any code
if(isset($_GET['redirect_to']))// && $_GET['redirect_to'] == 'destroySession') { $dbDetails = \upkar\php\ClassSiteConfig::getInstance()->getDBSettings(); switch($_GET['redirect_to']) { case "deleteAllCookiesAndSesstions": //http://localhost/pjt/upkar/upkar_site/public_html/deleteAllCookiesAndSesstions $sessionHelper->deleteAllCookiesAndSesstions();; exit; break; case "destroyDuplicateSession": $sessionHelper->destroyDuplicateSession(); exit; break; default: }//switch($_GET['redirect_to']) }//if(isset($_GET['redirect_to']))
-
finally initiate Session Handler Class just below that
|
|