Use PHP To Redirect To Another URL / Page

JordanTBH Knowledgebase / Browse the free Knowledgebase provided by JordanTBH Technologies.

With PHP you need to use header() to send a raw HTTP header. Using headers() method, you can easily transferred to the new page without having to click a link to continue. This is also useful for search engines. Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

Domain to Domain

This method is handy when you move a page from an old domain to newer domain in this case from example.com/about to jordantbh.me/about.

<?php
       // from example.com/about to jordantbh.me:
       header("Location: http://jordantbh.me/about");
?>

Path to Path

This method is handy when you move from one directory to another directory in this case from /pata to /patb.

<?php
       // from example.com/patha to example.com/patb:
       header("Location: /patb");
?>

Additional Notes
  1. Please note: The first example will not redirect all of your website to the newer domain, only on pages where the header() function is placed. If you need to do this take a look at the .htaccess 301 redirect method.
  2. The header() is used to send a raw HTTP/1.1 specification specific header. header() must be called before any actual HTML output is sent. This example will not work:
    <?php
           $var = "phpredirect";
           echo "Hello world";
           echo $var;
           /* Remember that header() must be called before any actual output is sent. */
           header("Location: http://network.jordantbh.me");
    ?>
                  

This article applies to the following:
  • PHP: Hypertext Preprocessor - Server-side HTML embedded scripting language. It provides web developers with a full suite of tools for building dynamic websites: native APIs to Apache.

Article incorrect or outdated? Do let us know →
Updated 18/01/14 @ 08:55 PM Luke Edwards, Editor