Summary: in this tutorial, you’ll learn how to use the PHP header()
function to redirect the web browser to a different URL.
Introduction to PHP redirection
The redirection allows you to redirect the web browser to a different URL. Typically, you use the redirection in the following cases:
- Change the domain name of a website to another.
- Replace the URL of a page with another.
- Upgrade the HTTP to HTTPS.
For example, suppose you have a page with the following URL:
https://www.phptutorial.net/about.php
Code language: PHP (php)
And you want to change it to:
https://www.phptutorial.net/about-us.php
Code language: PHP (php)
To do that, you use the header() function in the about.php like this:
<?php
header('Location: https://www.phptutorial.net/about-us.php', true, 301);
exit;
Code language: PHP (php)
When you navigate to the URL https://www.phptutorial.net/about-us.php, PHP will redirect you to the new URL https://www.phptutorial.net/about-us.php.
The following diagram illustrates how redirection works:
How it works.
- First, the web browser requests the URL
/about.php
from the server. - Second, the web server receives the request to the
/about.php
page and informs the web browser of the new URL:/about-us.php
. The web server also sends 301 HTTP code back. - Third, once the web browser receives the HTTP code 301, it requests the new URL
/about-us.php
- Finally, the server responds with the contents of the new URL
/about-us.php
.
PHP header() function
The header()
function has the following syntax:
header(string $header, bool $replace = true, int $response_code = 0): void
Code language: PHP (php)
The header() function sends a raw HTTP header. Therefore, you need to call it before sending any output.
To do it, you use the exit construct after calling the header() function.
The header()
function has the following parameters:
$header
specifies the HTTP header string to send. In the case of redirection, you use theLocation
header string for redirection.$replace
indicates if the header should replace the previous header.$response_code
is the HTTP status code to send back to the client.
Summary
- Redirection allows you to redirect a URL to the new one.
- Use the
header()
function to redirect a URL. - Call the
header()
function before any code that sends output to the web browser. - Use the
exit
construct immediately after theheader()
function.