How to Notify Clients Before Redirection by JavaScript

PHP provides a very useful function header() to redirect users to a proper page to proceed. For example, you demand users to login before using specific functions (e.g getmails.php), you can use header() to redirect users to the login page other than the request URI like this:

//getmails.php
...
if ($not_login) {
  header("Location: /login.php");
}
...

The advantage is that the transition is very fast, no extra network round-trip is needed and the users could hardly feel the redirection. But the drawback is no guidance or explanation to inform users what was happened there.

A more acceptable solution that you could adopt is to return an intermediate result to guide users through, which is using JavaScript to redirect user to the login page:

//getmails.php
...
if ($not_login) {
  $die <<<_END
<script>
  alert('Your session is expred, please login first.');
  window.location='/login.php';
</script>
_END;
  die($die);
}
...

In the above code, PHP will generate the intermediate result and terminate the script if the user is not logged in. From the user's point of view, an alert will show what will happen next before redirecting user to the login page. This could be more informative or explanatory than the first approach.

Leave a Reply

Your email address will not be published. Required fields are marked *