Andy Groom
Andy Groom

Reputation: 629

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?

Upvotes: 0

Views: 726

Answers (1)

Krzysztof Raciniewski
Krzysztof Raciniewski

Reputation: 4924

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 :)

Upvotes: 1

Related Questions