PHP: return life of current session - php

I am looking for a way to check on the life of a PHP session, and return the number of seconds a session has been "alive".
Is there a PHP function that I am missing out on?

You could store the time when the session has been initialized and return that value:
session_start();
if (!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
}
And for retrieving that information from an arbitrary session:
function getSessionLifetime($sid)
{
$oldSid = session_id();
if ($oldSid) {
session_write_close();
}
session_id($sid);
session_start();
if (!isset($_SESSION['CREATED'])) {
return false;
}
$created = $_SESSION['CREATED'];
session_write_close();
if ($oldSid) {
session_id($oldSid);
session_start();
}
return time() - $created;
}

I think there are two options neither are great but here they are.
1) If you have access to the file system you can check the creation timestamp on the session file.
2) Store the creation time in the session e.g.
session_start();
if( ! isset($_SESSION['generated'])) {
$_SESSION['generated'] = time();
}

You could simply store the timestamp on which the session was created in the session

Related

PHP Session Login Controller

I am trying to create a login controller for my website ... in terms of keeping people logged in I've decided to use sessions.
I am currently attempting to create a class that can be referenced when I include the controller file of the sessions. This will allow me to create, authenticate (delete) and update sessions.
<?php
class Session {
static function start($name, $value) {
session_start();
$_SESSION[$name] = $value;
$_SESSION['EXPIRE'] = time() + 10;
}
// checking for expire
static function auth() {
if (isset($_SESSION['EXPIRE']) && $_SESSION['EXPIRE'] < time()) {
$_SESSION = array();
session_destroy();
}
}
static function update($time = 20) {
if (isset($_SESSION['EXPIRE'])) {
$_SESSION['EXPIRE'] = time() + $time;
session_regenerate_id(false);
}
}
}
Currently it does not set sessions properly. When I try to call the sessions on pages once I set them it does not fetch properly.
The session isn't expiring before I call it because I never call the function that expires it inside the class on the document.
You can't call your Session class as you need to include session_start() and you are only having this in the start method.
Option 1: You would have to call session_start() in each page where you want to deal with sessions
Option 2: Add a function to your class and call it after your class is created and add in there session_start() so wherever you include the Session Class session_start would already been initialized
Example:
Sessions.php
class Session {
static function init(){
session_start();
}
//rest of your methods...
}
//initialize it
Session::init();
page-that-uses-session.php
include('Sessions.php');
Session::update();
Better set php session timeout variable in php.ini or from ini_set() function and don't create own $_SESSION['expire'] variable; You can regenerate_session_id() each time when user sent request; Better test user ip address in session. In most projects you have one page on server or only your own pages.
Set user id in session:
$_SESSION['userid'] = $loggoed_id_from_db;
// and test
if((int)$_SESSION['userid'] == 0){
header('Location: logout.php');
exit;
}else{
if(empty($_SESSION['ip'])){
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
}else{
if($_SESSION['ip'] != $_SERVER['REMOTE_ADDR']){
header('Location: logout.php');
exit;
}
}
}
And probably you don't start session from class!

How to change PHP session time in this code?

I am trying to change the session time in my login code, and here is the code I want to change the session time in:
<?php
if(session_id()==='')
{
session_start();
}
if(!(isset($_SESSION['status']) && $_SESSION['status'] == "logged_in"))
{
die("sorry, you must be logged in to view this page");
} else {
?>
How would I go about changing the session time?
Also, if you can't change the session time in this, is there any code that can replace this and still work the same?
You may try session_cache_expire
session_cache_expire(30);
$cache_expire = session_cache_expire();
or see this

PHP session_id regenerated on refresh

I am having problems with the session_id() that returns a new value every time on browser refresh/restart.
Read this post here but it doesn't solve the issue.I did all that was mentioned there - browser accepts cookies, permissions are set correctly, no param value is changed on sequential requests, etc.
Could this be refered to not using the session_name() or session_set_cookie_params() correctly? Or maybe it is the initial configuration that should be fine-tuned?
public static function init_session($name = FALSE, $lifetime = 10, $path = '/', $domain = FALSE, $secure = FALSE)
{
if (empty($name))
{
$name = APP_NAME;
}
if (empty($domain))
{
$domain = BASE_URL;
}
session_name($name);
session_set_cookie_params($lifetime, $path, $domain, $secure, TRUE);
session_start();
echo session_id();
}
First of all, you set your session lifetime to 10 seconds, which means that you get a new session after every 10 seconds.
Side note: It's normal behaviour for some browsers to discard session cookies when closing the browser.
If you need your session to expand over multiple browser sessions, you need to use persistent cookies.
Example:
function init_session(/* ... */)
{
if(!isset($_SESSION)) {
session_start();
}
//Is it a running session?
if(isset($_SESSION['somevalue'])) {
//Everything is fine, session is loaded, no need to reload from cookies
} else {
if(isset($_COOKIE['yourcookiename'])) {
//reload session from cookie
} else {
create_session();
}
}
}
function create_session()
{
$_SESSION['somevalue'] = 1;
//setcookie
}
Read http://www.allaboutcookies.org/cookies/cookies-the-same.html

PHP Session believes it's being hijacked unless an echo is performed

I'm writing a simple website which allows a user to login, fill out a form which is submitted to a database and then log out. In order to manage the session, I used the session manager which is described by TreeHouse on the following page: http://blog.teamtreehouse.com/how-to-create-bulletproof-sessions
In order to protect against hijacking, the client's IP address and user agent are stored in the session variable and compared to the server's values for these properties on each page. If they don't match, then it is assumed that the session has been hijacked and it is reset.
The implementation seems to work on my local machine without any issues, but when I uploaded it to the server, each page refresh causes the preventHijacking() function to return false (meaning it believes the session has been hijacked). However, if I echo any text within that function, the problem mysteriously disappears and the whole thing works as I expect it to (except for the bit of echoed text which is now displayed above my form :P).
I haven't a clue why this would be the case and I can't figure out how to fix it. The session manager code is below. At the start of each page, I use this to start the session and then each page simply uses or sets whatever variables it requires. If anyone could suggest why the function always returns false unless it echoes text and perhaps suggest what modification I need to make so that it will behave in the expected manner, I'd really appreciate it.
<?php
class SessionManager {
protected static $timeout = 600; // Time before automatic logout for the session
static function sessionStart($name, $limit=0, $path='/', $domain=null, $secure=null) {
// Set the cookie name before we start
session_name($name.'_Session');
// Set the domain to default to the current domain
$domain = isset($domain)? $domain : $_SERVER['SERVER_NAME'];
// Set the default secure value to whether the site is being accessed with SSL
$https = isset($secure)? $secure : isset($_SERVER['HTTPS']);
// Set the cookie settings and start the session
session_set_cookie_params($limit, $path, $domain, $secure, 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'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
self::regenerateSession();
// Give a 5% chance of the session ID changing on any request
} else if (rand(1, 100) <= 5) {
self::regenerateSession();
}
$_SESSION['LAST_ACTIVITY'] = time();
} else {
$_SESSION = array();
session_destroy();
session_start();
}
}
static function preventHijacking() {
if(!isset($_SESSION['IPaddress']) || !isset($_SESSION['userAgent'])) {
return false;
}
if($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR']) {
return false;
}
if($_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT']) {
return false;
}
return true;
}
static function regenerateSession() {
// If this session is obsolete, it means that 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']);
}
static protected function validateSession() {
// Check if something went wrong
if(isset($_SESSION['OBSOLETE']) && !isset($_SESSION['EXPIRES'])) {
return false;
}
// Test if this is an old session which has expired
if(isset($_SESSION['EXPIRES']) && $_SESSION['EXPIRES'] < time()) {
return false;
}
// Check if the user's login has timed out
if(isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > self::$timeout) {
return false;
}
return true;
}
}
?>
I could be way out here (it's been a while) but that sounds like the buffer containing the headers isn't being flushed for some reason. Providing body would force them to be flushed, so maybe not providing the body doesn't flush?
Try putting ob_end_flush(); in there before you return. That may fix it.

How to store sessions with PHP

I am trying to create a PHP session class to store sessions. What is the best way to deal with sessions?
This is what I have so far:
class Sessions {
function start() {
session_start();
$_SESSION['sid'] = randomstring();
// insert session id into db
// initialize user data
}
function destroy() {
session_destroy();
// delete sid from db too
}
function update() {
session_regenerate_id();
// update lastaccess time in db
}
}
What is the best way to store sessions in PHP?
This will answer your question of Session Handling? http://www.devshed.com/c/a/PHP/Storing-PHP-Sessions-in-a-Database/

Categories