PHP Redirection (original) (raw)

Skip to content

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:

For example, suppose you have a page with the following URL:

https://phptutorial.net/about.phpCode language: PHP (php)

And you want to change it to:

https://phptutorial.net/about-us.phpCode language: PHP (php)

To do that, you use the header() function in the about.php like this:

`<?php

header('Location: https://phptutorial.net/about-us.php', true, 301); exit;`Code language: PHP (php)

When you navigate to the URL https://phptutorial.net/about-us.php, PHP will redirect you to the new URL https://phptutorial.net/about-us.php.

The following diagram illustrates how redirection works:

PHP Redirection

How it works.

The header() function has the following syntax:

header(string <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>h</mi><mi>e</mi><mi>a</mi><mi>d</mi><mi>e</mi><mi>r</mi><mo separator="true">,</mo><mi>b</mi><mi>o</mi><mi>o</mi><mi>l</mi></mrow><annotation encoding="application/x-tex">header, bool </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">h</span><span class="mord mathnormal">e</span><span class="mord mathnormal">a</span><span class="mord mathnormal">d</span><span class="mord mathnormal" style="margin-right:0.02778em;">er</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">b</span><span class="mord mathnormal">oo</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span></span></span></span>replace = true, int $response_code = 0): voidCode 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:

Summary #

Did you find this tutorial useful?