1
votes

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?

2
No that actually should work, unless you've already sent some output. Do you get any errors? - Madara's Ghost
@Truth Most likely if he's calling and grabbing that information via AJAX, he's already had output (output is required for the AJAX call to take place?), so the headers can't be changed unless the page refreshed. - Josh Allen
The question is here is where this code is taking place. The AJAX call itself has not yet been sent the output, so it's still possible. Adam should reword his question and explain it better. - Madara's Ghost
@Truth I think with the information he's given us, we can safely assume his code is from an AJAX call. Either way I agree, the running of the code could be explained a little better. - Josh Allen

2 Answers

2
votes

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">'; 
} 
?>
1
votes

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 )