How to Redirect a Web Page in PHP

Unlike HTML and Javascript, which are downloaded from the Web server into the browser before being processed, server-side scripting languages like Hypertext Preprocessor (PHP) are first executed on the server before any data is sent to the browser. While both HTML and Javascript are capable of directing the Web browser to switch to a new page, both require that the browser first download a page containing the redirect code, process it, and then switch to the new page. Not only is this inefficient, but it relies on the browser to do the work, which may not happen if Javascript is disabled. PHP, on the other hand, will send a "302 moved" status code to the browser to redirect the browser before anything is actually downloaded. It's the difference between having an optional detour and closing down the alternate route altogether. With PHP, it's fast, invisible to the user, and can be done with as little as one line of PHP code.

Things You'll Need

  • Web server running PHP 4 or higher
  • Text editor
Show More

Instructions

    • 1

      On the very first line of a new file, type:

      <?php header("Location:http://domainname.com/newlocation"); ?>

      Do not leave any spaces, blank lines, or other characters in front of this code.

      If you wish to redirect a page from within a larger PHP script, simply place the header("Location:..."); function where you need it in your PHP code. Be sure that no spaces, blank lines, or other characters are sent to the Web browser before this function has a chance to run.

    • 2

      Save the file using your desired filename and an extension of .php:

      http://yourdomain.com/thisdirectory

      Save it as index.php if you will be redirecting from a directory instead of a filename:

      http://yourdomain.com/thisdirectory/file.php.

    • 3

      Upload the file to the desired location on the Web server and give it a quick test to make sure everything works as expected.

Tips & Warnings

  • These instructions will only work for .php files. If you wish to redirect from a non-PHP file, such as an .html file, then you'll need to redirect using a Web server configuration file such as .htaccess or else embed your redirect instructions in HTML or JavaScript.

  • It is very important that the PHP file containing the header() instructions does not write anything to the Web page before the header() function has a chance to run. This includes spaces, characters or blank lines preceding the <?php opening tag. Doing so will result in the Web server sending header information and that data before your script has a chance to send its custom header information. This will result in an error and failure.

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured