简体   繁体   中英

How to keep user logged in for one month in PHP?

I have searched all through StackOverflow and other forums, and have not found a way to make my code work. I have a basic login mechanism setup for my users, and it works just fine. However, when a browser is closed the user must visit the site and log back in. I need to find a way to keep the user logged in for a period of one month.

I researched cookies and experimented for two days, but consistently when I exit out of the browser and load the site back up, the user is logged out. The only thing that sort of worked was using ini_set to change the session.gc_maxlifetime and session.lifetime variables, but for some odd reason no matter what values I assigned to those two variables the user would only stay logged in for around 4 hours. So, does anyone know if I am doing something wrong in setting the cookie below, or how I can fix my problem? Thank you in advance for your answers, I am at my wits end with this issue.

        //create cookie, set expiration to one month (in seconds)

        setcookie("user",$username,time()+2592000);
        echo $_COOKIE["user"];

        session_start();

        //Login Successful, begin session

        $member = mysqli_fetch_assoc($result);
        $_SESSION['SESS_MEMBER_ID'] = $member['id'];
        $_SESSION['SESS_FIRST_NAME'] = $member['username'];
        $_SESSION['SESS_LAST_NAME'] = $member['password'];
        $_SESSION['table'] = $table;

        session_write_close();

        //header("location: search.php");
        exit();

In loggin page add (sessions):

$_SESSION['timeout'] = time();

and index check:

session_start();

$timeout = 7200; //time in seconds

if(isset($_SESSION['timeout'])) {
    $duracao = time() - (int) $_SESSION['timeout'];
    if($duracao > $timeout) {
      session_start();
      session_destroy();
      session_unset();
      echo "<script type='text/javascript'>location.href='index.php'</script>";
    }
}

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