Reputation: 20882
I have a number of AJAX calls that still partially work if the SESSION has expired.
eg: a contact us form will load, can be filled and appears to be sent but the AJAX call fails on the backend as SESSION variables don't exist.
I wanted to set a generic piece of PHP to check the session is still present like:
session_start();
<?php if(!isset($_SESSION['userid']) {header('Location: index.php');}?>
But nothing happens with this in place.
I'm assuming that header() will only work when the page is loading - is this correct?
Therefore I assume I will need to get the AJAX call to return a success or failure on the session and do the re-directing from JQUERY.
Is this the best way to do this? Can header() redirect on an AJAX call? is there another way to get the redirect to work from an AJAX PHP call?
thx
* UPDATE *
Yes the page has already loaded. The AJAX call is a post page load function sending a contactus request. Therefore I assume header() is a no go from what I've read here. header() would have been good as it could have sat at the top of a large PHP script and generically responded to any request where the session was set.
Looks like I'll have to build a check in for each AJAX call that uses the session. can use a generic function. Is there a more simple way to log a user out when the session has expired on an AJAX site?
Upvotes: 1
Views: 2701
Reputation: 2365
Update yor script as folows:
<?php
session_start();
if(!isset($_SESSION['userid']) {
echo 'true';
} else echo 'false';
?>
in jQuery check: if return true, than $_SESSION['userid'] is isset, else not isset )
Upvotes: 1
Reputation: 997
If it's an AJAX call, the headers for the page have already been sent, and therefore cannot be changed via an AJAX call. Instead, try a meta refresh in place of the header redirect:
<?php
session_start();
if(!isset($_SESSION['userid']) {
echo '<meta http-equiv="refresh" content="0; url=index.php">';
}
?>
Upvotes: 2