Jump to content

why session lifetime always 0


phat_hip_prog

Recommended Posts



// Start the session:
$seconds = 60;
$minutes = 60;
$hours = 24;
$days = 14;

session_set_cookie_params($seconds * $minutes * $hours * $days, "");
session_start();

you not show printing of stored expiry date!

 

i need to know if session cookie was last set to 0 or a time in future, you see i already set time in example

Link to comment
Share on other sites

Get the parameters after setting them.

$cookieParams = session_get_cookie_params();
session_set_cookie_params(time()+31536000, $cookieParams["path"], $cookieParams["domain"], false, true);

$cookieParams = session_get_cookie_params(); // get parameters

session_start();
echo "lifetime: ".$cookieParams["lifetime"]."<br />";
Link to comment
Share on other sites

You cannot use session_get_cookie_params()  to get the expiration date of an existing session cookie.

It is used to get the configuration values PHP will use when creating the session cookie.

 

 

If you need to evaluate the expiration of an existing session cookie, you should store the value in the session.

# check if there is a session cookie
if( ! isset($_COOKIE['SESSION_COOKIE_NAME']) ){
  // no session cookie: set parameters, start session, store cookie time in session
  $cookieTime = time()+31536000; 
  session_set_cookie_params($cookieTime, 'SESSION_COOKIE_PATH', 'SESSION_COOKIE_DOMAIN', false, true);
  session_start(); # start session
  $_SESSION['session_cookie_time'] = $cookieTime; # set session variable to remember time 
}else{
  // session cookie exists: start session, get cookie time, update cookie if required
  session_start(); # start session
  if( $_SESSION['session_cookie_time'] == SOME_VALUE ){
    $cookieTime = time()+31536000; # updated cookie time
    # update cookie using setcookie
    setcookie ( 'SESSION_COOKIE_NAME', session_id(), $cookieTime , 'SESSION_COOKIE_PATH' , 'SESSION_COOKIE_DOMAIN' , false );
    $_SESSION['session_cookie_time'] = $cookieTime; # update session variable to remember time
  }
}
Link to comment
Share on other sites

here's my latest version

 <?php

error_reporting(E_ALL);
ini_set('display_errors',E_ALL);

ini_set('session.use_only_cookies', 1);
$cookieParams = session_get_cookie_params();

$loggedin=true;
if(isset($_GET['logout'])){
	//session_set_cookie_params(-31536000, $cookieParams["path"], $cookieParams["domain"], false, true);
	session_set_cookie_params(0, $cookieParams["path"], $cookieParams["domain"], false, true);  
	session_start();
	//session_destroy();
	session_regenerate_id(true);
	//setcookie(session_name(), '', time()-42000, '/');
	session_unset();	//unset($_SESSION['myvar']);
	session_destroy();
	
	header("Location: http://". $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
	exit();
	
}elseif(isset($_GET['login'])){
	session_set_cookie_params(time()+31536000, $cookieParams["path"], $cookieParams["domain"], false, true);
	session_start();
	$_SESSION['myvar']="Logged in";
	header("Location: http://". $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
	exit();
	
}else{
	$cookieParams = session_get_cookie_params();
	echo "lifetime: ".$cookieParams["lifetime"]."<br />";
	/*
	if($cookieParams["lifetime"]>0){
		echo "lifetime: here<br />";
		session_set_cookie_params(time()+31536000, $cookieParams["path"], $cookieParams["domain"], false, true);
	//if($cookieParams["lifetime"]<=0){
	}else{
		echo "lifetime: There<br />";
		session_set_cookie_params(0, $cookieParams["path"], $cookieParams["domain"], false, true);
	}
	*/
	
	/*
	//echo "myvar222: ".$_SESSION['myvar']."<br />";
	//if(isset($_COOKIE['PHPSESSID'])){
	if(isset($_COOKIE[session_name()])){
		echo "here<br />";
		session_set_cookie_params(time()+31536000, $cookieParams["path"], $cookieParams["domain"], false, true);
	}else{
		echo "there<br />";
		session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], false, true);
	}
	*/
	
	session_set_cookie_params(0, $cookieParams["path"], $cookieParams["domain"], false, true);
	session_start();
	
	if(isset($_SESSION['myvar'])){
		//session_write_close();
		session_set_cookie_params(time()+31536000, $cookieParams["path"], $cookieParams["domain"], false, true);
		//session_start();
		session_regenerate_id(false);
	}
	
}

//session_regenerate_id();
echo session_id()."<br />";

if(isset($_SESSION['myvar'])){
	echo "myvar: ".$_SESSION['myvar']."<br />";
	echo "<a href='?logout=true'>logout</a><br />";
}else{
	echo "<a href='?login=true'>login</a><br />";
}
?>
Link to comment
Share on other sites

ok I understand the setcookie overwrite, wasn't thinking :)

 

but when i test for the cookie existence on reopening the browser i'm logged out, see commented out bit in the else.

 

however using setcookie() does stop me having to regen the session id

 

<?php
error_reporting(E_ALL);
ini_set('display_errors',E_ALL);

ini_set('session.use_only_cookies', 1);
$cookieParams = session_get_cookie_params();

$loggedin=true;
if(isset($_GET['logout'])){
	session_set_cookie_params(0, $cookieParams["path"], $cookieParams["domain"], false, true);  
	session_start();
	session_regenerate_id(true);
	session_unset();	//unset($_SESSION['myvar']);
	session_destroy();
	
	header("Location: http://". $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
	exit();
	
}elseif(isset($_GET['login'])){
	session_set_cookie_params(time()+31536000, $cookieParams["path"], $cookieParams["domain"], false, true);
	session_start();
	$_SESSION['myvar']="Logged in";
	header("Location: http://". $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
	exit();
	
}else{
	/*
	if(isset($_COOKIE[session_name()])){
		echo "here<br />";
		session_set_cookie_params(time()+31536000, $cookieParams["path"], $cookieParams["domain"], false, true);
	}else{
		echo "there<br />";
		session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], false, true);
	}
	*/
	
	session_set_cookie_params(0, $cookieParams["path"], $cookieParams["domain"], false, true);
	session_start();
	
	if(isset($_SESSION['myvar'])){
		setcookie(session_name(), session_id(), time()+31536000 , $cookieParams["path"], $cookieParams["domain"], false, true);
	}
}

echo session_id()."<br />";

if(isset($_SESSION['myvar'])){
	echo "myvar: ".$_SESSION['myvar']."<br />";
	echo "<a href='?logout=true'>logout</a><br />";
}else{
	echo "<a href='?login=true'>login</a><br />";
}

?>
both ways in your example set the time to non zero, i also need to handle session only users

 

thanks for all help ;)

Link to comment
Share on other sites

Sorry, you don't keep a user logged in by altering the session cookie expiration time.

The session cookie expiration time and the session max lifetime are independent values, so setting the session cookie expiration far into the future does not guarantee the session is alive on the server when the user revisits with that session cookie.

Link to comment
Share on other sites

i don't alter the expiry date willy nilly, as is, it sets it to a future date if logged in and 0 if not logged in so that the session isn't carried over after the browser is closed

 

i'm just trying to preset the session cookie rather than doing it after,,, because, if you don't click "accept all cookies from this site" then you are prompted to accept a cookie (every page request), but if you preset the cookie then you aren't prompted all the time

Link to comment
Share on other sites

When a user logs in, you should start a session and create a session variable to store the id of the user that logged in.

$auth_user = false;  # define auth_user and set to false ( no user logged in )

if(isset($_GET['logout'])){
     session_start();
     unset($_SESSION['user']);  # unset the session variable used to store id of the user
     session_destory();
     header("Location: http://". $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
     exit();
}elseif(isset($_GET['login'])){
    session_start();
    $_SESSION['user']=USER_ID;  # SET USER ID HERE!
    header("Location: http://". $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
    exit();
}else{
    session_start();
    if(isset($_SESSION['user']) && $_SESSION['user']){
        $auth_user = $_SESSION['user'];
    }
}
Edited by objnoob
Link to comment
Share on other sites

When a user logs in, you should start a session and create a session variable to store the id of the user that logged in.


$auth_user = false;  # define auth_user and set to false ( no user logged in )

if(isset($_GET['logout'])){
     session_start();
     unset($_SESSION['user']);  # unset the session variable used to store id of the user
     session_destory();
     header("Location: http://". $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
     exit();
}elseif(isset($_GET['login'])){
    session_start();
    $_SESSION['user']=USER_ID;  # SET USER ID HERE!
    header("Location: http://". $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
    exit();
}else{
    session_start();
    if(isset($_SESSION['user']) && $_SESSION['user']){
        $auth_user = $_SESSION['user'];
    }
}

 

that code doesn't handle "stay logged in"

Link to comment
Share on other sites

Sure it does.  As long as the session cookie is valid and the session is alive. The user is treated as being logged in (authenticated)!

but what about after they close the browser and then reopen it? to do that youd need to set the expiry date to non zero, but if you set the expiry date non zero for all then even if not logged in and reopen browser then their session id persists (not the session vars because we invalidated them)

Link to comment
Share on other sites

First, you should add a checkbox to the login form that says 'Remember Me'.

 

Next, we'll modify the code implement the remember me feature...

$auth_user = false;  # define auth_user and set to false ( no user logged in )

if(isset($_GET['logout'])){
     session_start();
     unset($_SESSION['user']);  # unset the session variable used to store id of the user
     session_destory();
     header("Location: http://". $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
     exit();
}elseif(isset($_GET['login'])){

    # authenticate user; start session
    
     session_start();
     $_SESSION['user']=USER_ID;  # SET USER ID HERE!
    
    # if the user checked remember me
    if(isset($_GET['chkRememberMe']) && $_GET['chkRememberMe']){
         # the user did check remember me, create an login key cookie that lasts a long time
         $key = $username .':'. sha256($user_id.$password.'iM_a_HaRdCoDeD_SaLt');
         setcookie('login_key', $key, time()+31536000); 
    }

    header("Location: http://". $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
    exit();
}else{
    session_start();
    if(isset($_SESSION['user']) && $_SESSION['user']){
        $auth_user = $_SESSION['user'];
    }else{
        # user is not logged in, lets check for a auto login key
        if(isset($_COOKIE['login_key'])){
            # key found, process authentication using this key.
            list($username, $key) = explode($_COOKIE['login_key']);
         
            # get the user id and user password from the database using the username found in the key
            # we store user_id into $user_id, and password into $password
            
            # now authenticate the key
            if($key === sha256($user_id.$password.'iM_a_HaRdCoDeD_SaLt')){
                # key is valid
                $_SESSION['user'] = $user_id;    
                header("Location: http://". $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
                exit;
            }
                        

        }
    }
}
Link to comment
Share on other sites

using $_GET is out of the question!!! (oops you are only doing that for the form, not my choice of handling web forms)

 

i think you are missing the point about session lifetimes, something your code is still missing

 

the stay logged in checkbox was purposely missed out for simplicity of the example code

 

 

as i said the code i posted works fine, but i have to set the session cookie twice because i can't check before starting the session, even though to avoid extra cookie popups you have to set the session cookie lifetime before starting the session. in reality i'm just looking for a neater, more efficient and less intrusive way!

 

in your code, you should add something semi random to the key hash, say time (in your case last login time say), as it is the key will be the same across all that users logins, so it'd only need to be cracked once!!!

 

 

* in a production environment i have an install salt and a user specific salt, but if doing a hash i'd also add time in somewhere else all you have to do is check the keyspace of the max salt size, not very safe!

Link to comment
Share on other sites

Are you smoking crack?

 

1. i chose $_GET because you're using $_GET already

2. the key is derived from the user's password or password hash. if the user changes password, any old auto login keys will fail authentication.

3. adding something random makes no sense. you can't authenticate randoms!

4. keeping a session open on your server indefinitely is pretty stupid. hello session hijacking!

 

Anyways, I'm not here to write the code to your exact specifications. I'm here to show an example of how it could be done with no warranties implied!

Edited by objnoob
Link to comment
Share on other sites

Are you smoking crack?

Hell yeah!

1. i chose $_GET because you're using $_GET already

see!!

2. the key is derived from the user's password or password hash. if the user changes password, any old auto login keys will fail authentication.

3. adding something random makes no sense. you can't authenticate randoms!

 

you store it!

4. keeping a session open on your server indefinitely is pretty stupid. hello session hijacking!

that's called "stay logged in" and its a year not indefinitely!

show me a way using cookies which isn't susceptible to session hijacking?

 

 

and if you'd be so kind show me these flaws its riddled with?

 

Anyways, I'm not here to write the code to your exact specifications. I'm here to show an example of how it could be done with no warranties implied!

all i ever really asked was if it was possible to get the expiry before starting the session since you set the params first, never asked you to write owt kid ;) the code worked in the first place, just looking for someone who understood achieving it without resetting the session cookie, your example was retrograde whilst telling me it was better!!!
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.