How can I stop an AJAX call while maintaining a PHP session

I have an authentication system in my site using CakePHP. For this, it uses PHP sessions.

What I have in place is an AJAX call (within setInterval, executed every minute) of a function that checks if the user is all logged in. If it returns false, then Javascript takes the current URL and tries to redirect it, which in turn redirects them to the login page. Theoretically, this works because it actively asks the user to re-enter the system instead of having an obsolete session that simply asks them to log in as soon as they click something. My problem is that my AJAX call supports the session. Therefore, we never exit the system (which we do not need)

Is there anything I can do in CakePHP or any other methods I can use to stop this?

+4
source share
7 answers

Add &ajax= (whatever) to the query string when you validate the session.

Then change the PHP session code:

 session_start(); if(!isset($_GET["ajax"])) $_SESSION["lastactivity"] = time(); if(now() - $_SESSION["lastactivity"] > 3600){ //3600 seconds header("Location: login.php?url="+urlencode(str_replace("&ajax=", "", $_SERVER["REQUEST_URI"]))); //Example: // Location: login.php?url=/sensible/secret.php?mode=show&hide=nothing exit; } 
+2
source

The AJAX pigment that you described is most often used for this - keeping the session in active mode. The fact that you accessed your application during an active session updates it.

You can do one of the following:

  • have a fixed-length session, for example. 30 minutes, after which it always expires (not sure if this is a good idea) and keep ping
  • change the logic so that you do not ping at all, and when the session expires and the user either goes to a new page or performs an AJAX session, the server returns the corresponding status code and / or redirects the user to the login page.

I would go with the second option.

0
source

The obvious ways to do this are:

  • don't call session_start () at the Ajax endpoint
  • implement your own session handler using backdoor, which allows you to skip part of the record (for example, based on the state of the global variable or the current URL).

As an ugly hack, you can try calling session_id ('dummy'); or change the session handler after calling session_start () at the Ajax endpoint.

0
source

As I mentioned in the comment, you can create a javascript file with the following contents and call this file on all your pages

 setTimeout("checkSession()",1800000); function checkSession(){ //alert("Your session has expired due to inactivity. You will be logged out"); window.location.reload();//or window.location="logoutAction"; } 
0
source

I do not think that you can only rely on an Auth session for this.

What I would do is create a new field in the user table to track the latest activity, for example last_activity as mysql timestamp. Then in your AppController::beforeFilter() set this field to update with the current datetime (this will happen with every request), but set it to skip this if this is your pinging action that makes the request (you can check $this->here or even add your own parameter for other actions too).

Your Ajax pin is obviously just reading this field, and if you are more than x minutes ago, you are logged out.

0
source

This does not exactly answer the question you ask, but I think this is the best practice that I would like to share.

setInterval () does not behave as you expected. This does not mean that your code will be executed every minute, it guarantees that your code will be added to the queue every minute.

The problem is that the timer code may not complete before adding the code to the queue. The result will be that the timer code is run several times in a row, without any time between them. Fortunately, JavaScript engines are smart enough to avoid this problem. When using setInterval (), the timer code is added to the queue only if there are no other instances of the timer code already in the queue. This ensures that the time between additions of the timer code to the queue is at least the specified interval.

The disadvantage of this regulation of repeating timers is twofold: (1) the intervals can be skipped, and (2) the intervals can be less than expected between several runs of the time code ... -N. Zakas, Professional JavaScript for Web Developers

How to do this, you need to format your timer code as follows:

 setTimeout( function() { // code to be run setTimeout( arguments.callee, *interval* ); }, *interval* ); 

note: arguments.callee cannot be used in strict mode.

0
source

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...

0
source

All Articles