Here I got a solution to determine if the session was alive or not.
No overhead needed. We can detect and redirect the session timeout to regular HTTP requests. Where, as in ajax, we will have to relate to it differently, with some logic.
# step 1 (server side)
In the php side. First, create an authentication function that should call this authorization on the first line of the entire page.
It is best to add this auth () function to the config.php file or auth.php file and include it in all php file after creating the session.
enable 'config / auth.php';
// in auth.php file copy and past the following lines function auth() { if (!isset($_SESSION['USER_ID'])) { // checking whether the request is ajax or not. Ajax requests are xml http request if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { // set a status code manually. 418 is unused http code header("HTTP/1.0 418 Session Timeout", TRUE); // return or send a json response with status string and location to redirect echo json_encode(array( "status" => "time_out", "location" => BASE_URL . "login.php?message=Session Timeout! Please log in and Try again.", )); exit; } // whether the request is normal http request do the redirection from the server side if (basename($_SERVER['PHP_SELF']) != 'login.php') { header("Location:" . BASE_URL . "login.php"); } } }
# step 2 (client side)
Here I use jQuery create a js file that should call all the html (template) pages in the project.
Itβs best to include in the header or footer
create ajax settings
$.ajaxSetup({ statusCode: { 418: function (respose) { // $.parseJSON() can avoid by specifying dataType:"json" in ajax parameters var jsonObject = $.parseJSON(respose.responseText); if (jsonObject.status == "time_out") { window.location = jsonObject.location; } } } });
To have a good day...
source share