简体   繁体   中英

php keep session alive for multiple days

I have an app where I would like to enable users to choose to stay logged in for a fairly long period of time, say 3 days similar to google mail, facebook or linkedin. (It is meant to be accessed primarily by phone and data is far less sensitive than other stuff on phone.) Right now I am setting about four session variables on log in, such as id of user, name, etc. so to avoid a lot of recoding and lost functionality, I'd like all of these variables to remain accessible.

Is there a way to increase session length to 72 hours when setting the session variables?

Alternatively, if you need to set cookies, what is best practice to achieve long logged in time when there are a number of session variables set.

Thanks.

You can set session for various ways. One of the ways is to set it in php.ini

session.gc_maxlifetime = 360*72

with php you can do it with

ini_set(’session.gc_maxlifetime’, 360*72);

you can also use

session_set_cookie_params(360*72,"/");

http://pl1.php.net/session_set_cookie_params

it sets session cookie. You can also serialize $_SESSION and set it in cookie.

I guess it is possible only by writing session to database

you can set a long live cookie & check value of the same on user request after many days.

use cookie value as a key in table to validate user identity.

then reload session of that user from database.

Maybe you could use the session storage of local storage features of HTML 5 ?

I know it is not purely the same thing as cookies, but I just wanted to propose this. Maybe it could help :)

There might be a little version problem with older versions of browser on phones. You can check them with : http://caniuse.com/namevalue-storage

And there's another thing. You can use "Remember Me" cookies for long term storage of important informations. Extending the lifetime of cookie is, as far as I know, not a "good practice".

You can do this by sending a post every 5 minutes to a php function that stores the session id in a variable, then destroys the session, creates it again and gives the session id again:

<?php

function restart_session(){

    $user_session = $_SESSION['id'];

    session_destroy();
    session_start();

    $_SESSION['id'] = $user_session;

}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM