Problem with a specific php session class - php

I am currently writing a PHP site for myself. Now I am trying to secure my site. Therefor I am using session. I don't want to write one for myself so I searched and found a wonderful example.
<?php
class SessionManager
{
static function sessionStart($name, $limit = 0, $path = '/', $domain = null, $secure = null)
{
// Set the cookie name
session_name($name . '_Session');
// Set SSL level
$https = isset($secure) ? $secure : isset($_SERVER['HTTPS']);
// Set session cookie options
session_set_cookie_params($limit, $path, $domain, $https, true);
session_start();
// Make sure the session hasn't expired, and destroy it if it has
if(self::validateSession())
{
// Check to see if the session is new or a hijacking attempt
if(!self::preventHijacking())
{
// Reset session data and regenerate id
$_SESSION = array();
$_SESSION['IPaddress'] = isset($_SERVER['HTTP_X_FORWARDED_FOR'])
? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
$_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
self::regenerateSession();
// Give a 5% chance of the session id changing on any request
}elseif(rand(1, 100) <= 5){
self::regenerateSession();
}
}else{
$_SESSION = array();
session_destroy();
session_start();
}
}
/**
* This function regenerates a new ID and invalidates the old session. This should be called whenever permission
* levels for a user change.
*
*/
static function regenerateSession()
{
// If this session is obsolete it means there already is a new id
if(isset($_SESSION['OBSOLETE']) || $_SESSION['OBSOLETE'] == true)
return;
// Set current session to expire in 10 seconds
$_SESSION['OBSOLETE'] = true;
$_SESSION['EXPIRES'] = time() + 10;
// Create new session without destroying the old one
session_regenerate_id(false);
// Grab current session ID and close both sessions to allow other scripts to use them
$newSession = session_id();
session_write_close();
// Set session ID to the new one, and start it back up again
session_id($newSession);
session_start();
// Now we unset the obsolete and expiration values for the session we want to keep
unset($_SESSION['OBSOLETE']);
unset($_SESSION['EXPIRES']);
}
/**
* This function is used to see if a session has expired or not.
*
* #return bool
*/
static protected function validateSession()
{
if( isset($_SESSION['OBSOLETE']) && !isset($_SESSION['EXPIRES']) )
return false;
if(isset($_SESSION['EXPIRES']) && $_SESSION['EXPIRES'] < time())
return false;
return true;
}
/**
* This function checks to make sure a session exists and is coming from the proper host. On new visits and hacking
* attempts this function will return false.
*
* #return bool
*/
static protected function preventHijacking()
{
if(!isset($_SESSION['IPaddress']) || !isset($_SESSION['userAgent']))
return false;
if( $_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT']
&& !( strpos($_SESSION['userAgent'], ÔTridentÕ) !== false
&& strpos($_SERVER['HTTP_USER_AGENT'], ÔTridentÕ) !== false))
{
return false;
}
$sessionIpSegment = substr($_SESSION['IPaddress'], 0, 7);
$remoteIpHeader = isset($_SERVER['HTTP_X_FORWARDED_FOR'])
? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
$remoteIpSegment = substr($remoteIpHeader, 0, 7);
if($_SESSION['IPaddress'] != $remoteIpHeader
&& !(in_array($sessionIpSegment, $this->aolProxies) && in_array($remoteIpSegment, $this->aolProxies)))
{
return false;
}
if( $_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT'])
return false;
return true;
}
}
?>
I am trying to call the function over:
include 'SessionSafe.php';
SessionManager::sessionStart('InstallationName');
i am testing the session with:
if (!isset($_SESSION['userid'])) {
header('Location: Login.php');
}
Before, I wrote a value in $_SESSION['userid'], but I have the problem that the session variable is empty...

//File1.php
include 'SessionSafe.php';
session_start();
SessionManager::sessionStart('InstallationName');
// file2.php
session_start();
if (!isset($_SESSION['userid'])) {
header('Location: Login.php');
}
You still have to use session start at the top of each php file.

Related

Losing session data in code igniter

I am facing problems with session data. After login to the website, I'm losing session data. I have tired creating sessions in database and also tried native php session class but nothing worked. I have also cleared tmp folder from server.
The website uses code igniter framework and it is hosted on godaddy VPS
Please help me. Thank You...
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class CI_Session {
var $session_id_ttl; // session id time to live (TTL) in seconds
var $flash_key = 'flash'; // prefix for "flash" variables (eg. flash:new:message)
function CI_Session()
{
$this->object =& get_instance();
log_message('debug', "Native_session Class Initialized");
$this->_sess_run();
}
/**
* Regenerates session id
*/
function regenerate_id()
{
// copy old session data, including its id
$old_session_id = session_id();
$old_session_data = $_SESSION;
// regenerate session id and store it
session_regenerate_id();
$new_session_id = session_id();
// switch to the old session and destroy its storage
session_id($old_session_id);
session_destroy();
// switch back to the new session id and send the cookie
session_id($new_session_id);
session_start();
// restore the old session data into the new session
$_SESSION = $old_session_data;
// update the session creation time
$_SESSION['regenerated'] = time();
// session_write_close() patch based on this thread
// http://www.codeigniter.com/forums/viewthread/1624/
// there is a question mark ?? as to side affects
// end the current session and store session data.
session_write_close();
}
/**
* Destroys the session and erases session storage
*/
function destroy()
{
//unset($_SESSION);
session_unset();
if ( isset( $_COOKIE[session_name()] ) )
{
setcookie(session_name(), '', time()-42000, '/');
}
session_destroy();
}
/**
* Reads given session attribute value
*/
function userdata($item)
{
if($item == 'session_id'){ //added for backward-compatibility
return session_id();
}else{
return ( ! isset($_SESSION[$item])) ? false : $_SESSION[$item];
}
}
/**
* Sets session attributes to the given values
*/
function set_userdata($newdata = array(), $newval = '')
{
if (is_string($newdata))
{
$newdata = array($newdata => $newval);
}
if (count($newdata) > 0)
{
foreach ($newdata as $key => $val)
{
$_SESSION[$key] = $val;
}
}
}
/**
* Erases given session attributes
*/
function unset_userdata($newdata = array())
{
if (is_string($newdata))
{
$newdata = array($newdata => '');
}
if (count($newdata) > 0)
{
foreach ($newdata as $key => $val)
{
unset($_SESSION[$key]);
}
}
}
/**
* Starts up the session system for current request
*/
function _sess_run()
{
$session_id_ttl = $this->object->config->item('sess_expiration');
if (is_numeric($session_id_ttl))
{
if ($session_id_ttl > 0)
{
$this->session_id_ttl = $this->object->config->item('sess_expiration');
}
else
{
$this->session_id_ttl = (60*60*24*365*2);
}
}
session_start();
// check if session id needs regeneration
if ( $this->_session_id_expired() )
{
// regenerate session id (session data stays the
// same, but old session storage is destroyed)
$this->regenerate_id();
}
// delete old flashdata (from last request)
//$this->_flashdata_sweep();
// mark all new flashdata as old (data will be deleted before next request)
//$this->_flashdata_mark();
}
/**
* Checks if session has expired
*/
function _session_id_expired()
{
if ( !isset( $_SESSION['regenerated'] ) )
{
$_SESSION['regenerated'] = time();
return false;
}
$expiry_time = time() - $this->session_id_ttl;
if ( $_SESSION['regenerated'] <= $expiry_time )
{
return true;
}
return false;
}
/**
* Sets "flash" data which will be available only in next request (then it will
* be deleted from session). You can use it to implement "Save succeeded" messages
* after redirect.
*/
function set_flashdata($key, $value)
{
$flash_key = $this->flash_key.':new:'.$key;
$this->set_userdata($flash_key, $value);
}
/**
* Keeps existing "flash" data available to next request.
*/
function keep_flashdata($key)
{
$old_flash_key = $this->flash_key.':old:'.$key;
$value = $this->userdata($old_flash_key);
$new_flash_key = $this->flash_key.':new:'.$key;
$this->set_userdata($new_flash_key, $value);
}
/**
* Returns "flash" data for the given key.
*/
function flashdata($key)
{
$flash_key = $this->flash_key.':old:'.$key;
return $this->userdata($flash_key);
}
/**
* PRIVATE: Internal method - marks "flash" session attributes as 'old'
*/
function _flashdata_mark()
{
foreach ($_SESSION as $name => $value)
{
$parts = explode(':new:', $name);
if (is_array($parts) && count($parts) == 2)
{
$new_name = $this->flash_key.':old:'.$parts[1];
$this->set_userdata($new_name, $value);
$this->unset_userdata($name);
}
}
}
/**
* PRIVATE: Internal method - removes "flash" session marked as 'old'
*/
function _flashdata_sweep()
{
foreach ($_SESSION as $name => $value)
{
$parts = explode(':old:', $name);
if (is_array($parts) && count($parts) == 2 && $parts[0] == $this->flash_key)
{
$this->unset_userdata($name);
}
}
}
}
Always prefer to create sessions based on the framework's format. Even I too had the same problem. At that time I was using codeigniter version 2.0, so I used the frameworks session definitions. But as far as I know $_SESSION global variable is supported in version 3
Adding Custom Session Data
$this->session->userdata('item');
$this->session->set_userdata($array);
Retrieving Session Data
$this->session->userdata('item');
Retrieving All Session Data
$this->session->all_userdata()
Removing Session Data
$this->session->unset_userdata('some_name');
Check this documentation, you could get a clear view
https://ellislab.com/codeigniter/user-guide/libraries/sessions.html
When there are any page redirections, keep "exit" after redirect code.
That is how I solved my problem (losing session data after page redirection). See the below example.
header("Location: example.php");
exit;

How to override session_set_save_handler() with user defined functions?

I am trying to save the session in a database instead of files on the server. I have defines the session_set_save_handler() like so
//Set handler to override SESSION
session_set_save_handler( array($this, "open"),
array($this, "close"),
array($this,"read"),
array($this, "write"),
array($this,"destroy"),
array($this, "gc"));
But I keep getting this warning
Undefined variable: this
Then I tried changing it to
session_set_save_handler( "open", "close", "read", "write", "destroy", "gc" );
I don't get the error but I get the following warning
Warning: session_set_save_handler(): Argument 1 is not a valid callback
this is my open() function
static protected function open(){
// If successful return true
if($this->db)
return true;
return false;
}
My question is how can I properly override the function?
this is my entire class
<?php
class SessionManager {
/**
* AOL users may switch IP addresses from one proxy to another.
*
* #link http://webmaster.info.aol.com/proxyinfo.html
* #var array
*/
protected $aolProxies = array('195.93.', '205.188', '198.81.', '207.200', '202.67.', '64.12.9');
private $db;
/**
* This function starts, validates and secures a session.
*
* #param string $name The name of the session.
* #param int $limit Expiration date of the session cookie, 0 for session only
* #param string $path Used to restrict where the browser sends the cookie
* #param string $domain Used to allow subdomains access to the cookie
* #param bool $secure If true the browser only sends the cookie over https
*/
static function sessionStart($dbo, $name, $limit = 0, $path = '/', $domain = null, $secure = null)
{
$this->db = $dbo;
//Set the cookie name
session_name($name); //. '_Session'
//Set SSL level
$https = isset($secure) ? $secure : isset($_SERVER['HTTPS']);
//Set session cookie options
session_set_cookie_params($limit, $path, $domain, $https, true);
//Set handler to override SESSION
session_set_save_handler( "open", "close", "read", "write", "destroy", "gc" );
session_start();
// Make sure the session hasn't expired, and destroy it if it has
if(self::validateSession()){
// Check to see if the session is new or a hijacking attempt
if(!self::preventHijacking()){
// Reset session data and regenerate id
$_SESSION = array();
$_SESSION['IPaddress'] = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
$_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
self::regenerateSession();
// Give a 5% chance of the session id changing on any request
} elseif(rand(1, 100) <= 5)
self::regenerateSession();
} else {
$_SESSION = array();
session_destroy();
session_start();
}
}
/*
* This function regenerates a new ID and invalidates the old session. This should be called whenever permission
* levels for a user change.
*/
static function regenerateSession(){
// If this session is obsolete it means there already is a new id
if(isset($_SESSION['OBSOLETE']) || $_SESSION['OBSOLETE'] == true)
return;
// Set current session to expire in 10 seconds
$_SESSION['OBSOLETE'] = true;
$_SESSION['EXPIRES'] = time() + 10;
// Create new session without destroying the old one
session_regenerate_id(false);
// Grab current session ID and close both sessions to allow other scripts to use them
$newSession = session_id();
session_write_close();
// Set session ID to the new one, and start it back up again
session_id($newSession);
session_start();
// Now we unset the obsolete and expiration values for the session we want to keep
unset($_SESSION['OBSOLETE']);
unset($_SESSION['EXPIRES']);
}
/*
* This function is used to see if a session has expired or not.
* #return bool
*/
static protected function validateSession(){
if( isset($_SESSION['OBSOLETE']) && !isset($_SESSION['EXPIRES']) )
return false;
if(isset($_SESSION['EXPIRES']) && $_SESSION['EXPIRES'] < time())
return false;
return true;
}
/*
* This function checks to make sure a session exists and is coming from the proper host. On new visits and hacking
* attempts this function will return false.
*
* #return bool
*/
static protected function preventHijacking(){
if(!isset($_SESSION['IPaddress']) || !isset($_SESSION['userAgent']))
return false;
if( $_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT']
&& !( strpos($_SESSION['userAgent'], 'Trident') !== false
&& strpos($_SERVER['HTTP_USER_AGENT'], 'Trident') !== false))
return false;
$sessionIpSegment = substr($_SESSION['IPaddress'], 0, 7);
$remoteIpHeader = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
$remoteIpSegment = substr($remoteIpHeader, 0, 7);
if($_SESSION['IPaddress'] != $remoteIpHeader
&& !(in_array($sessionIpSegment, $this->aolProxies) && in_array($remoteIpSegment, $this->aolProxies)))
return false;
if( $_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT'])
return false;
return true;
}
//Open the database connection
private function open(){
// If successful return true
if($this->db)
return true;
return false;
}
//Close the database connection
static protected function close(){
// If successful return true
if($this->db->endConnection())
return true;
return false;
}
//Read the session information
private function read($id){
//Select session data
$info = $this->db->getOneResult('SELECT data FROM sessions WHERE id = ?', array($id) );
//if data found return it
if($info)
return $info['data'];
// Return an empty string
return '';
}
//Write the session information
private function write($id, $data){
// Create time stamp
$access = time();
// Set query
$write = $this->db->processQuery('REPLACE INTO sessions VALUES (?, ?, ?)', array($id, $access, $data));
// If successful return true
if($write)
return true;
// Return False
return false;
}
//Destroy
private destroy($id){
//Delete record
$delete = $this->db->processQuery('DELETE FROM sessions WHERE id = ?',array($id) );
// Attempt execution
// If destroyed return true
if( $delete )
return true;
// Return False
return false;
}
//Garbage Collection
private function gc($max){
// Calculate what is to be deemed old
$old = time() - $max;
//Delete old sessions
$delete = $this->db->processQuery('DELETE FROM sessions WHERE access < ?', array($old));
//if Garbage has been removed return true
if($delete)
return true;
// Return False
return false;
}
}
?>
You are defining it in a static method. $this does not exist in static methods.
You can use the classname itself. So you would do something like:
//Set handler to override SESSION
session_set_save_handler( array("SessionManager", "open"),
array("SessionManager", "close"),
....);
first
//Destroy
private destroy($id){
change
//Destroy
public function destroy($id){

Check if a User is Logged On In a PHP Login System

I'm relatively new to PHP and have been making a PHP login system. It works fine and all, but I'm wondering if there's a cleaner and more efficient way to check if a user is logged in. At the current moment my code looks like this:
session_start();
if(isset($_SESSION['username']))
{
Echo "*Whole bunch of HTML*";
}
else{
header("location:index.php");
end();
}
I want to make it to where the if statement checks if the user is logged in and nothing more, rather than having the if statement check if the user is logged in then displaying the page within in the if statement. Is this possible?
You are doing things ok. But here is what I do for my code:
function checklogin() {
if (!$this->isLoggedIn())
return false;
else
return true;
}
function isLoggedIn() {
if (isset($_SESSION['user_id']) && isset($_SESSION['user_email'])) {
if( !$this->isTimeOut() )
return false;
$where = array(
'id' => $_SESSION['user_id'],
'email' => $_SESSION['user_email']
);
//this is database class method
$value['data'] = $dataBaseClass->login_access($where);
if ($value['data'] != FALSE && $_SESSION['user_id'] == $value['data']->id && $_SESSION['user_email'] == $value['data']->email) {
return true;
}
/*
username or userlevel not exist or s_ecryption session invalid
User not logged in.
*/
else
return false;
}
/**
* cookie check for user login || you can escape this
*/
else if (isset($_COOKIE['cookie_key']) && $_COOKIE['cookie_key'] != '') {
$cookie_key = $_COOKIE['cookie_key'];
$where = array(
'cookie_key' => $cookie_key
);
$user_data = $databaseClass->login_access($where);
if (!empty($user_data)) {
$_SESSION['user_id'] = $user_data->id;
$_SESSION['user_email'] = $user_data->email;
return true;
}
} else {
return false;
}
}
Make a library/functions file, write above code, include that file in class files you need and call the function.
Hope this helps.

Modx Pagelocker logout

I made a page that is locked by Pagelocker. This works perfect but now I need a logout link/button. So I made a link which links to a logout.php.
In this logout.php there is following code:
<?php
session_start();
unset($_SESSION);
session_destroy();
session_write_close();
header("Location: /login.html");
die;
exit;
?>
It redirects me to login but when I manually go to protected page it is shown without login.
The code which is used to protect the page and start the session is:
<?php
/**
*
* PageLocker
*
* Simple front-end password protection for individual or groups of pages.
*
* # author Aaron Ladage (mods by Bob Ray)
* # version 1.1.0-beta1 - June 21, 2012
*
* PLUGIN PROPERTIES
* &tvPassword - (Required) The TV for the password (default: 'pagePassword')
* &tvPasswordGroup - The TV for the password group (default: 'pagePasswordGroup'). Not required, but a good idea, unless you want all password-protected pages to be accessible with the same password.
* &formResourceID - (Required) The ID of the password form page (no default set, but absolutely necessary -- the plugin will not work without it)
*
**/
/* #var $modx modX */
/* #var $scriptProperties array */
if (!function_exists("toForm")) {
/* Show Login form */
function toForm($resourceId) {
global $modx;
unset($_SESSION['password']); // make sure password is not still set
if ($modx->resource->get('id') != $resourceId) { // prevent infinite loop
$modx->sendForward($resourceId);
}
}
}
// Get the default plugin properties
$tvPassword = $modx->getOption('tvPassword',$scriptProperties,'pagePassword');
$tvPasswordGroup = $modx->getOption('tvPasswordGroup',$scriptProperties,'pagePasswordGroup');
$formResourceID = $modx->getOption('formResourceID', $scriptProperties);
// Get the password and password group values from the page's template variables
$resourcePW = $modx->resource->getTVValue($tvPassword);
$resourceGroup = $modx->resource->getTVValue($tvPasswordGroup);
/* Do nothing if page is not password-protected, or the form page is not set in the properties */
if ((empty($resourcePW)) || (empty($formResourceID))) {
return;
}
// Set additional defaults
$resourceGroup = empty($resourceGroup) ? 0 : $resourceGroup;
$groups = isset($_SESSION['groups'])? $modx->fromJSON($_SESSION['groups']) : array();
/* Get and sanitize the password submitted by the user (if any) */
$userPW = isset($_POST['password'])? filter_var($_POST['password'], FILTER_SANITIZE_STRING) : '';
if (!empty($userPW)) { /* Form was submitted */
if ($userPW == $resourcePW) { /* password matches the page's password */
/* Set the logged in and groups session */
$_SESSION['loggedin'] = 1;
if (! in_array($resourceGroup, $groups)) {
$groups[] = $resourceGroup;
$groupsJSON = $modx->toJSON($groups);
$_SESSION['groups'] = $groupsJSON;
}
return;
} else { // Doesn't match. Back to the form!
toForm($formResourceID);
}
} else { // Form wasn't submitted, so check for logged in and groups sessions
if ( empty($groups) || ! isset($_SESSION['loggedin']) || (! $_SESSION['loggedin'] === 1) || (! in_array($resourceGroup, $groups))) {
toForm($formResourceID);
}
}
I really need help for this.
As explained in the documentation, there is a little more that needs to be done besides making a call to session_destroy to completely obliterate a session.
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(
session_name(),
'',
time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_destroy();

Troubles with Codeigniter's Native Session

I'm using Codeigniter's Native Session Class for storing users information, but i have a serious problem. It appears that the session times out when the user is inactive for about half an hour and logs him out.
My config file looks like this:
$config['sess_cookie_name'] = 'cisession';
$config['sess_expiration'] = 60*60*24*30*12*2;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = FALSE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 7200;
The PHPSESSID in browser is not destroyed when the user is logged out and it expires in two years as I've set it in config file.
I don't know what are the common problems with native session class because everyone seems to be happy with it, so can somebody work it out what is the most likely thing that is causing this problem?
Edit: For those who aren't familiar with codeigniter's native session class here is link
http://codeigniter.com/wiki/Native_session
i use also codeigniter's native class. Maybe you not config it correctly. Here is code that i get from him. https://github.com/EllisLab/CodeIgniter/wiki
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class CI_Session {
var $session_id_ttl; // session id time to live (TTL) in seconds
var $flash_key = 'flash'; // prefix for "flash" variables (eg. flash:new:message)
function __construct()
{
log_message('debug', "Native_session Class Initialized");
$this->object =& get_instance();
$this->_sess_run();
}
/**
* Regenerates session id
*/
function regenerate_id()
{
// copy old session data, including its id
$old_session_id = session_id();
$old_session_data = $_SESSION;
// regenerate session id and store it
session_regenerate_id();
$new_session_id = session_id();
// switch to the old session and destroy its storage
session_id($old_session_id);
session_destroy();
// switch back to the new session id and send the cookie
session_id($new_session_id);
session_start();
// restore the old session data into the new session
$_SESSION = $old_session_data;
// update the session creation time
$_SESSION['regenerated'] = time();
// session_write_close() patch based on this thread
// http://www.codeigniter.com/forums/viewthread/1624/
// there is a question mark ?? as to side affects
// end the current session and store session data.
session_write_close();
}
/**
* Destroys the session and erases session storage
*/
function destroy()
{
unset($_SESSION);
if ( isset( $_COOKIE[session_name()] ) )
{
setcookie(session_name(), '', time()-42000, '/');
}
session_destroy();
}
/**
* Reads given session attribute value
*/
function userdata($item)
{
if($item == 'session_id'){ //added for backward-compatibility
return session_id();
}else{
return ( ! isset($_SESSION[$item])) ? false : $_SESSION[$item];
}
}
/**
* Sets session attributes to the given values
*/
function set_userdata($newdata = array(), $newval = '')
{
if (is_string($newdata))
{
$newdata = array($newdata => $newval);
}
if (count($newdata) > 0)
{
foreach ($newdata as $key => $val)
{
$_SESSION[$key] = $val;
}
}
}
/**
* Erases given session attributes
*/
function unset_userdata($newdata = array())
{
if (is_string($newdata))
{
$newdata = array($newdata => '');
}
if (count($newdata) > 0)
{
foreach ($newdata as $key => $val)
{
unset($_SESSION[$key]);
}
}
}
/**
* Starts up the session system for current request
*/
function _sess_run()
{
session_start();
$session_id_ttl = $this->object->config->item('sess_expiration');
if (is_numeric($session_id_ttl))
{
if ($session_id_ttl > 0)
{
$this->session_id_ttl = $this->object->config->item('sess_expiration');
}
else
{
$this->session_id_ttl = (60*60*24*365*2);
}
}
// check if session id needs regeneration
if ( $this->_session_id_expired() )
{
// regenerate session id (session data stays the
// same, but old session storage is destroyed)
$this->regenerate_id();
}
// delete old flashdata (from last request)
$this->_flashdata_sweep();
// mark all new flashdata as old (data will be deleted before next request)
$this->_flashdata_mark();
}
/**
* Checks if session has expired
*/
function _session_id_expired()
{
if ( !isset( $_SESSION['regenerated'] ) )
{
$_SESSION['regenerated'] = time();
return false;
}
$expiry_time = time() - $this->session_id_ttl;
if ( $_SESSION['regenerated'] <= $expiry_time )
{
return true;
}
return false;
}
/**
* Sets "flash" data which will be available only in next request (then it will
* be deleted from session). You can use it to implement "Save succeeded" messages
* after redirect.
*/
function set_flashdata($key, $value)
{
$flash_key = $this->flash_key.':new:'.$key;
$this->set_userdata($flash_key, $value);
}
/**
* Keeps existing "flash" data available to next request.
*/
function keep_flashdata($key)
{
$old_flash_key = $this->flash_key.':old:'.$key;
$value = $this->userdata($old_flash_key);
$new_flash_key = $this->flash_key.':new:'.$key;
$this->set_userdata($new_flash_key, $value);
}
/**
* Returns "flash" data for the given key.
*/
function flashdata($key)
{
$flash_key = $this->flash_key.':old:'.$key;
return $this->userdata($flash_key);
}
/**
* PRIVATE: Internal method - marks "flash" session attributes as 'old'
*/
function _flashdata_mark()
{
foreach ($_SESSION as $name => $value)
{
$parts = explode(':new:', $name);
if (is_array($parts) && count($parts) == 2)
{
$new_name = $this->flash_key.':old:'.$parts[1];
$this->set_userdata($new_name, $value);
$this->unset_userdata($name);
}
}
}
/**
* PRIVATE: Internal method - removes "flash" session marked as 'old'
*/
function _flashdata_sweep()
{
foreach ($_SESSION as $name => $value)
{
$parts = explode(':old:', $name);
if (is_array($parts) && count($parts) == 2 && $parts[0] == $this->flash_key)
{
$this->unset_userdata($name);
}
}
}
}
PHPs sessions expires after 1440 seconds (24 minutes).
http://php.net/manual/en/session.configuration.php

Categories