Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

javascript - How can i stop an AJAX call keeping a PHP Session alive

I have an authentication system on my site using CakePHP. It uses PHP Sessions for this.

What i have in place is an AJAX call (within a setInterval running every minute) to a function which checks if the user is still logged in. If it returns false, then the Javascript takes the current URL and attempts to redirect them, which in turn redirects them to the login page. In theory this works because it actively asks the user to re-login instead of holding a stale session which will just ask them to login as soon as they click something. My problem is that my AJAX call is keeping the session alive. So never get logged out (which we don't want)

Is there ANYTHING i can do within CakePHP or any other methods i can use to stop this happening?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Add &ajax= (anything) to the query string when you're checking for the validity of the session.

Then, alter your 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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...