How to Redirect With PHP

Use This Webpage Redirect Script When You Remove a Page

Detour
 iStock / Getty Images Plus

When you remove one of your webpages, it's a good idea to set up a redirect, so anyone who bookmarked that page is transferred automatically to an active page on your website. You can use a simple PHP script to redirect a user from the page they entered to a different webpage. Using this method, you seamlessly transfer visitors to the webpage that no longer exists to the new page without requiring them to click a link to continue.

Benefits of a PHP Redirect

The benefits of this PHP script are:

  • Users are redirected quickly and seamlessly.
  • When users click the Back button, they are taken to the last viewed page, not the redirect page.
  • The redirect works on all web browsers.

Use the Header Function to Redirect

The header() function sends a raw HTTP header. It must be called before any output is sent, either by normal HTML tags, by PHP or by blank lines.

Change the code on the redirect page to read: 

<?php

   header( 'Location: http://www.yoursite.com/new_page.html' ) ;

?>

You replace the URL in this sample code with the URL of the page where you want to redirect visitors. Transfer visitors to a different webpage on your site or a different website entirely.

Because this includes the header() function,  sure that you do not have any text sent to the browser before this code, or it will not work. Your safest bet is to remove all the content from the page except for the redirect code.

Tips for Setting Up a Redirect

  • Remove all code but this redirect script.
  • Mention on the new page that users should update their links and bookmarks.
  • Use this code to create a drop-down menu that redirects users.
Format
mla apa chicago
Your Citation
Bradley, Angela. "How to Redirect With PHP." ThoughtCo, Feb. 12, 2018, thoughtco.com/how-to-redirect-with-php-2693922. Bradley, Angela. (2018, February 12). How to Redirect With PHP. Retrieved from https://www.thoughtco.com/how-to-redirect-with-php-2693922 Bradley, Angela. "How to Redirect With PHP." ThoughtCo. https://www.thoughtco.com/how-to-redirect-with-php-2693922 (accessed February 23, 2018).