trilithium.net

How to redirect to another page

How do I redirect to another page using HTML or PHP?

Two mechanisms are commonly used when you want to redirect the user from one page to another automatically: the Refresh and Location headers. Refresh is the easiest, because most browsers will let you use it in a HTML document:

<meta http-equiv="refresh" content="5; url=http://www.trilithium.net/">

The above meta element, when placed in the head part of your HTML document, would take a user to the URL http://www.trilithium.net/ after 5 seconds. You can specify any number of seconds to wait, including 0. Always use absolute rather than relative URLs when redirecting.

The refresh mechanism may also be used to automatically reload a page on a regular basis:

<meta http-equiv="refresh" content="60">

This will make a browser reload the page automatically once every 60 seconds. Be careful with this directive, and make sure you don't use too small a refresh interval; it's easy to cause lots of unnecessary traffic which will slow the web server down.

Using meta http-equiv with Refresh may be easy but it has a couple of drawbacks: it tends to break the user's back button and it won't work in every case because it relies on the client to parse HTML. Many search engines will be unable to follow such a redirection unless you also include a regular link on the page.

When using PHP, you can redirect the proper way by sending HTTP response headers along with your page. This is done through the header function:

header('Location: http://www.trilithium.net/');
exit;

The call to exit immediately after the call to header() is there to avoid sending any further output from the page. The response also needs a correct HTTP status code (302) in order to redirect, but PHP will take care of that for us.

If you need a delay before sending the visitor to the next page, Refresh can be used with PHP's header header function as well:

header('Refresh: 5;url=http://www.trilithium.net/');

This is somewhat more reliable than using meta http-equiv, but Refresh is not part of the HTTP specification (at least not yet), so there's no guarantee browsers will support it.