In this tutorial, you’ll find comprehensive guidance on how to perform page redirection in PHP. The key topics covered include redirecting to a different URL using the location header, redirecting with or without the header() function, and how to avoid a common mistake associated with redirection. The objective is to equip you with the necessary knowledge to implement efficient page redirection techniques in your PHP projects.  To complement your understanding of PHP Header Redirect, it’s essential to explore another critical aspect of PHP, which is mail validation.

The Mechanisms of Web Redirection

Redirection is a fundamental aspect of web development, facilitating the seamless transition of users from one web page to another. It is the automatic process that occurs when a web page is accessed, directing the user to a different URL. A technical understanding of how redirection works is essential for web developers and designers.

There are two primary stages in which redirection can occur:

  • Pre-Page Load Redirection: This type of redirection takes place before any content from the requested page (page A) is delivered to the user. For example, when a user submits a form, they are immediately redirected to a “thank you page,” bypassing the need to display the form again;
  • Post-Page Load Redirection: Post-page load redirection occurs after the initial URL (page A) has been loaded in the user’s web browser. Subsequently, the browser is redirected to a different URL (page B), either immediately or after a brief delay. An example of this is often encountered after completing an online payment, where a payment confirmation page informs the user of an impending redirection to the main store page.

For those interested in implementing these redirection operations in PHP, we will provide a technical guide in our upcoming tutorial. This guide will walk you through the PHP code required to achieve both pre and post-page load redirection effectively. Mastery of redirection control and utilization is a valuable skill for web development professionals.

URL Redirection in PHP Using the header() Function

In PHP, you can execute a page redirection using the header() function, which is a commonly employed method for directing users to different URLs within a web application. This technical guide will illustrate how to use the header() function for URL redirection.

Here’s a practical example:

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


The argument passed to the header() function consists of two parts:

  • A fixed “Location: ” string;
  • The URL to which the user should be redirected.

Upon execution of the header() function, the remote user is immediately directed to the specified URL. This type of redirection is instantaneous, with no web content being transmitted to the user before redirection occurs.

The destination URL should typically be an absolute URL, such as “https://www.google.com.” However, many web browsers also accept relative URLs, which can be convenient when redirecting to a resource within your own website. For example:

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

It is crucial to call the die() function after using header() for redirection. Failing to do so may result in the script’s execution continuing after the redirection, potentially causing unintended behavior or errors in your web application.

Proper Use of header() Function and Output in PHP

a computer screen with php word on it and keyboard on white table with flower and red cup on it

In PHP, the header() function serves the purpose of sending an HTTP header to the web browser. This header instructs the browser to initiate a redirection to a different URL. To ensure the correct functioning of this function, it is imperative to call header() before any output is transmitted to the browser. This includes various types of content, such as:

  • Any HTML content located outside of the PHP tags;
  • Any text or data that is printed using PHP.

To provide a clearer understanding of this requirement, let’s examine three incorrect examples:

Mistake Example #1: HTML Output Before header()

<html>
<?php
header('Location: https://www.google.com/');
die();
 
Mistake Example #2: Printing Text with PHP Before header()

echo 'Redirecting...';
header('Location: https://www.google.com/');
die();
 
Mistake Example #3: Blank Line Before header() (Occurs with Empty Lines Before PHP Opening Tag)

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

But what if the redirection needs to occur after some output has already been sent?

In such scenarios, you have three available options:

  • Save the output in a variable (instead of using echo or similar commands);
  • Employ output buffering;
  • Utilize front-end redirection.

The first solution is the most straightforward. Instead of employing echo or similar commands to produce output, you collect all the output within a variable. Subsequently, you only display the variable if no redirection is required.

For instance:

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

Now, let’s delve into the concept of output buffering in PHP.

Output buffering allows your PHP script to retain all generated output until the script’s execution concludes. Essentially, it accomplishes the task you need without necessitating the explicit use of variables.

Using output buffering is straightforward. You simply need to invoke ob_start() to initiate the buffering process and then ob_end_flush() to send all buffered content at the desired point.

Here’s a practical illustration of how it operates:

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

Now, let’s explore the mechanism of front-end redirection.

Redirection Using an HTML Meta Tag

An alternative method for achieving redirection is by employing a specific HTML meta tag. This meta tag must be incorporated into the HTML page generated via PHP. Once the browser loads the page, it interprets the redirection tag and carries out the redirection process.

In contrast to PHP-based redirection, this approach does not result in an immediate redirection. The browser first loads the initial page before executing the redirection.

Here is an example:

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

The redirection tag is essentially an HTML meta tag with the attribute “http-equiv” set to “refresh,” and the “content” attribute containing two components:

  • A numerical value specifying the number of seconds to delay before initiating the redirection. If set to 0, the redirection is immediate. This number is followed by a semicolon (;);
  • The new URL in the format “url=new_url.” If this component is not specified, the current URL is reloaded, effectively functioning as an auto-refresh.

Redirection Using JavaScript

Instead of relying on the HTML meta tag, an alternative approach to achieve redirection is by utilizing JavaScript.

In JavaScript, the command for redirection is executed through the window.location.replace() function. To trigger redirection, you need to invoke this function at the appropriate point in your code, typically after the page has finished loading.

Here’s an example illustrating the JavaScript redirection method:

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

If you prefer to initiate redirection after a specified timeout period, you can achieve this by employing the standard JavaScript setTimeout() function, as demonstrated below:

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 in PHP

woman holding webpage near the big tablet with website on it

Now, let’s revisit the PHP header() redirection method, with a focus on HTTP redirect codes.

When using the header() function for redirection, you have the option to specify an additional HTTP redirection code.

Redirections are typically implemented for two primary reasons:

  • When you want to guide the user to a different web page, as seen in the form submission example;
  • When an URL has permanently moved to a new address, and you want to ensure that all requests to the old URL are redirected to the new one.

When you transmit the redirection header, you can also inform the web browser about the purpose of the redirection by sending the appropriate HTTP header. This is particularly relevant for Search Engine Optimization (SEO) purposes.

Specifically, you should consider sending:

  • A 301 code when the page has permanently moved to the new URL;
  • A 302 code when the page has temporarily moved to the new URL.

By default, the header() function sends a 302 code, indicating a temporary redirection. If you intend to send a 301 code because the old URL has permanently moved to the new URL, you must specify it explicitly. This can be achieved by sending a 301 header before the redirection header, as shown below:

<?php
Header( "HTTP/1.1 301 Moved Permanently" );
header('Location: https://www.google.com/');
 
Alternatively, you can use the third argument of the header() function to specify the response code directly:

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

Conclusion

In this tutorial, the technical aspects of PHP redirection using the header() function were covered. Emphasis was placed on avoiding output before redirection. The tutorial also delved into front-end redirection techniques employing HTML meta tags and JavaScript, along with specifying redirection types using HTTP response codes such as 301 and 302.

Leave a Reply

Your email address will not be published. Required fields are marked *