Delayed Redirect in PHP

I’ve seen a number of different ways discussed on how to achieve the “wait and redirect” effect entirely in PHP. This type of functionality could easily be achieved in JavaScript using a setTimeout coupled with an anonymous function to send the user on their way to the next location; however, in PHP it gets a little tricky.

Here’s how to accomplish this in JavaScript.

var new_location = 'http://www.seanasullivan.com';
setTimeout(function(){window.location = new_location},2000);

In PHP, you have to deal with the limitation that you cannot output anything to the page before the headers. And since setting headers is the way by which we need to redirect the user, we need to find the appropriate valeus to set so we can also display a friendly message to the user, such as “Currently Redirecting” or “Thank You for Logging in! We are now redirecting you to your account.”

If you didn’t need to output anything to the screen, there’s a sleep() function available in PHP which will delay your code from being executed for the amount of time specified. You could use this, quickly followed by the header() function to send the user off. In my opinion, this is not a desireable implementation

The “refresh” header, is the correct way to accomplish this effect. By setting the pages header to refresh, you gain the ability to define a delay, in seconds, followed by the url in which the user should be sent after the delay.

header("Refresh: 3; http://www.seanasullivan.com");

This results in a header that looks like this in HTML form:

<meta http-equiv="Refresh" content="0; url=http://www.seanasullivan.com/">

One caveat with this issue is that it does “break” the back button on the browser. In some ways, it may not be a big deal; however, as clicking back after being redirected simply takes the user back to the page before the one they were redirect from. In my most recent implementation this isn’t an issue because I was using the redirect after the user logged into a site. So the flow looked like:

Login Form -> Succesful Logs in Message (trigger redirect) -> Account Page

In this case, once the user lands on the Account Page, clicking back on the browser takes them to the Login Form. Like I said, not an issue in this case, but beware, you may encounter circumstances that you need to be sensitive to this.