PHP Redirect Tutorial

How to redirect to another page with PHP.

 
PHP redirect
 

In this tutorial you’ll learn how to redirect in PHP.

We are going to see:

  • How to redirect to another URL by sending a location header.
  • How to redirect with or without using the header() function.
  • The most common mistake and how to avoid it.
  • …and more.

Let’s dive right in.

Contents


How redirection works.

Redirection happens when you open a web page and you are sent automatically to a different URL.

Redirections can happen at two stages.

Let’s say that you go to page A, and then you are redirected to page B. This redirection can happen:

  1. Before page A is loaded. Or,
  2. After page A is loaded.

In the first case, you are immediately sent to page B before any content is received from page A.

An example of this is a form submission page: when you fill and submit the form, the page automatically redirects you to a different “thank you page”, without showing the form again.

In the second case, you open the first URL and your browser loads page A. After that, your browser is sent to page B, immediately or after a timeout.

This type of redirection happens often after an online payment: the payment confirmation page tells you that you are going to be redirected to the store’s page in a few seconds.

Now, let’s see how you can perform these operations in PHP.

How to redirect in PHP: the header() function.

In PHP, you can do a page redirect with the header() function.

Let’s see an example right away:

header('Location: https://www.google.com/');
die();

The argument of the header() function is a string made of two parts:

  1. A fixed “Location: “ part.
  2. The URL where to redirect the user.

As soon as the header() function is executed, the remote user is redirected to the new URL.

This is an “immediate” redirect: the user does not receive any web content before the redirection.

The destination URL should be an absolute URL, like: https://www.google.com.

However, most browsers accept relative URLs too. This can be handy if you want to redirect to a relative URL on your own website.

For example:

$thankyou_page = 'thank_you.php';
if ($form_data_valid) {
	header('Location: ' . $thankyou_page);
	die();
}

NOTE:

You should always call die() after header(). Otherwise, the script execution may continue after the redirection.

Redirection and output.

The header() function sends an HTTP header to the browser. This header tells the browser to go to a different URL.

It’s important to call header() before any output is sent to the browser, including:

  • Any HTML outside of the PHP tags.
  • Any text or data printed with PHP.

To better understand what that means, here are three wrong examples.

Wrong example #1: HTML output before header()

<html>
<?php
header('Location: https://www.google.com/');
die();
 

Wrong example #2: text printed with PHP before header()

echo 'Redirecting...';
header('Location: https://www.google.com/');
die();
 

Wrong example #3: a white line before header() (this happens if you leave one or more empty lines before the PHP opening tag)


<?php
header('Location: https://www.google.com/');
die();
 

But what if the redirection comes after some output has already been sent?

In these cases, you have three choices:

  • Save the output in a variable (instead of echoing it).
  • Use output buffering.
  • Use front-end redirection.

The first solution is the easiest. Basically, instead of using echo or similar commands, you save all the output inside a variable.

Then, you output the variable only if no redirection occurs.

For example:


$html = '<html><head></head>';
$redirect = TRUE;
if ($redirect) {
   
   header('Location: https://www.google.com/');
   die();
}
else {
   echo $html;
}
 

Now let’s look at output buffering.

Output buffering makes your PHP script keep all the output until the end of the script.

So, basically, it does exactly what you need without having to use variables explicitly.

Using output buffering is very simple. You just need to call ob_start() when you want the buffer to begin, and then ob_end_flush() when you want all the buffer to be sent.

Here’s how it works:

<?php
ob_start();
?>
<html>
<head></head>
<?php
$redirect = TRUE;
if ($redirect) {
   header('Location: https://www.google.com/');
   die();
}
ob_end_flush();
 

Now, let’s see how front-end redirection works.

Redirect with an HTML meta tag.

Another way to perform a redirection is to use a specific HTML meta tag.

This tag must be added to the HTML page that you generate with PHP. After the browser has loaded the page, it reads the redirection tag and executes it.

Contrary to the PHP redirect, this is not an immediate redirect, because the browser loads the first page before performing the redirection.

Let’s see an example:

<html>
   <head>
      <meta http-equiv="refresh" content="0; url=https://www.google.com/">
   </head>
   <body>
   ...
   </body>
</html>
 

The redirection tag is an HTML meta tag with the http-equiv=”refresh” attribute, and the content attribute containing:

  • A number that tells how many seconds to wait before the redirection. If set to 0, the redirection is immediate. This number is followed by a ;
  • The new URL, in the form url=new_url. If this is not set, then the current URL is loaded again (so, in practice, it works as an auto-refresh).

Redirect with JavaScript.

Instead of using the HTML meta tag, you can also use JavaScript to perform a redirect.

In JavaScript, the redirection command is performed by the window.location.replace() function.

You need to make the page execute this function when you want to perform the redirection, which is usually right after the page is loaded.

For example:

<html>
  <head>
    <script>
      function goToGoogle()
      {
        window.location.replace('https://www.google.com');
      };
    </script>
  </head>
  <body onload="goToGoogle();">
  </body>
</html>
 

If you want to redirect after a timeout, you can simply use the standard JavaScript setTimeout() function.

Like this:

<html>
  <head>
    <script>
      function redirectWithTimeout()
      {
        setTimeout(goToGoogle, 5000);
      }
      
      function goToGoogle()
      {
        window.location.replace('https://www.google.com');
      };
      </script>
  </head>
  <body onload="redirectWithTimeout();">
    <p>You will be redirected in 5 seconds.</p>
  </body>
</html>

HTTP redirect codes.

Let’s go back to the PHP header() redirection.

When you redirect using the header() function, you can also specify an optional redirection HTTP code.

Redirection is done for two reasons:

  1. You simply want to move the user to a different page, like in the form submission example.
  2. You have moved an URL to a different address, so you want to redirect all the requests to the first URL to the second.

When you send the redirection header, you can also tell the browser the reason why this redirection happens by sending the appropriate HTTP header.

This is mostly relevant for SEO purposes.

In particolar, you want to send:

  • a 301 code if the page has moved permanently to the new URL
  • a 302 code if the page has moved temporarily to the new URL

By default, the header() function sends a 302 code – a temporary redirection.

If you want to send a 301 code instead, because the old URL has moved permanently to the new URL, then you must specify it explicitly.

You can do it by sending a 301 header before the redirection header. Like this:

<?php
Header( "HTTP/1.1 301 Moved Permanently" );
header('Location: https://www.google.com/');
 

You can also use the third header() argument to specify the response code:

<?php
header('Location: https://www.google.com/', TRUE, 301);

Conclusion

In this tutorial you learned how to redirect with PHP.

You saw how to use the header() function and how to avoid sending output before the redirection.

You also saw how to perform front-end redirection with an HTML meta tag and with JavaScript, and how to specify the redirection type (301 and 302).

Do you have any questions? Then leave a comment below and I’ll get back to you.

And be sure to subscribe to my free newsletter to get my weekly tips!

Alex

When you code in PHP, do you still feel like a beginner?

Get more confident about your PHP skills with 5 learning strategies. Get the free PDF now.

Image copyright: Decision vector created by vectorjuice – www.freepik.com

4 thoughts on “PHP Redirect Tutorial”

Leave a Comment