how to expire php session if user is inactive for 15 mins

后端 未结 6 522
无人及你
无人及你 2020-12-04 22:48

i have created one project in PHP, into which i am managing sessions.

I am creating session in my config.php file by writing following line of code.

         


        
6条回答
  •  北海茫月
    2020-12-04 23:20

    I know this is an answered question but I just wanted to share my experience and since I feel like this is a more easy approach. I'm not sure if this is the best way but here goes. What I did was:

    1. I set a PHP Session ($_SESSION['timeout']) to current time (time()) when the user logged in.

    2. Wrote the following function to validate whether the user is active.

    function sessionTimeOut() {

    // This function is adding 900 seconds (15 Minutes, which is the amount of time you want the user to // be inactive to automatically logout) to the previously registered time when the user was last active. // Then, its checking whether the current time is greater than the amount of time you want the user to // stay logged in without timing out (which is 15 minutes). If it's greater, then you are redirected to the // login page where you can initiate a logout function with http://www.yourwebpage/login.php?status=timeout on the URL.

    if ($_SESSION['timeout'] + 900 > time()) {

      // User Active so reset time session.
      $_SESSION['timeout'] = time();
    

    } else {

      // session timed out then redirect to login page
      header('Location:http://'. $_SERVER[HTTP_HOST] . '/login.php?status=timeout');
    

    }

    }

    Lastly: Call sessionTimeOut(); function in the header after checking if user is logged in. This allows the function to be called every time the user refreshes or navigates to a new page. Thus, it works perfectly (atleast in my case), fulfils my purpose, so I thought I'd just share it with you guys.

提交回复
热议问题