Redirecting The Page In PHP

13th January 2008 - 3 minutes read time

To redirect the current page to a different location you use the header() function in the following way:


You can use this function when you want to point the user to a different page. If you are writing a login script then this function would be useful to show the user a certain page depending on them entering the correct user information.

To send a code along with the redirect (for example, a 301) you can use the optional parameters. The second parameter is a boolean value that determines if this header call should replace any headers of a similar name. For example, if you send a header called "Cache-Control" and then send another header later on with the same name then the second parameter determines if the value is replaced or appended. If the value is true then the previous value is overwritten, if the value is false then the value is appended to the list of headers being sent.

The third parameter is the code to be issued along with the header. So to create a 301 redirect do the following.


The is a problem with the headers() function is that it will cause errors if any output has already been sent to the browser, including other headers. To get around this you can use the headers_sent() function, which checks to see if any headers have been sent. If they have then it returns true, if not then false is returned. So with this in mind we can create a neat little check to redirect the page in both cases. If headers have already been sent then the JavaScript property location.href can be used to redirect the page in the same way.

  1. // set up redirect URL
  2. $url = "";
  3. if ( headers_sent() ) {
  4. // redirect using JavaScript if it has
  5. echo "<script type="text/javascript">
  6. <!--//--><![CDATA[// ><!--
  7. location.href='$url';
  8. //--><!]]>
  9. </script>";
  10. exit();
  11. } else {
  12. // otherwise use the php way.
  13. header("Location:".$url);
  14. exit();
  15. }

This works as long as the user has JavaScript turned on, if they don't then you might have to just provide them with a link to allow them to progress.

Add new comment

The content of this field is kept private and will not be shown publicly.