简体   繁体   中英

How to deal with a PHP session timeout

I've got an area of a webpage which displays a timesheet and the user can click left and right to go forward / back a week:

<script type="text/javascript">
 var TimesheetOffset = 0;
 function TimesheetNav(AdjustBy) {
   TimesheetOffset = TimesheetOffset + AdjustBy;
   $("#timesheets").load("populate_timesheets.php?start=" + TimesheetOffset);
 }
</script>

The populate_timesheets.php script displays the timesheet information in a DIV area with the id of "timesheets", but only if the user is logged in and their session hasn't expired - if the session has expired it displays a login page:

    if (!isset($_SESSION['login_user'])) {
        header("location: index.php");
    }

The problem is that if the session has timed-out, the index.php script appears where the timesheet should be displayed rather than replacing the entire page. How can I alter either the PHP or the JavaScript so that if the session has timed-out the login page replaces the entire page?

JavaScript code:

$.ajax("populate_timesheets.php?start=" + TimesheetOffset, {
   type: "GET",
   statusCode: {
      401: function (response) {
         // redirect to login page
      }
   }, 
   success: function (data) {
      $( "#timesheets" ).html(data);
   },
   error: function (error) {
      console.log('Error occured: ', error);
   }
});

PHP code:

if (!isset($_SESSION['login_user'])) {
    header("HTTP/1.1 401 Unauthorized");
    return;
}

I don't test this code, so if you have problem, read jQuery documentation about AJAX Requests :)

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