Saturday, October 11, 2025
HomeLanguagesHow to make a redirect in PHP?

How to make a redirect in PHP?

Redirection from one page to another in PHP is commonly achieved using the following two ways:
Using Header Function in PHP: 
The header() function is an inbuilt function in PHP which is used to send the raw HTTP (Hyper Text Transfer Protocol) header to the client. 
Syntax: 

header( $header, $replace, $http_response_code )

Parameters: This function accepts three parameters as mentioned above and described below: 
 

  • $header: This parameter is used to hold the header string.
  • $replace: This parameter is used to hold the replace parameter which indicates the header should replace a previous similar header, or add a second header of the same type. It is optional parameter.
  • $http_response_code: This parameter hold the HTTP response code.

Below program illustrates the header() function in PHP:
Program: 

php




<?php
 
// Redirect browser
header("Location: https://www.geeksforgeeks.org");
 
exit;
?>


Note: The die() or exit() function after header is mandatory. If die() or exit() is not put after the header(‘Location: ….’) then script may continue resulting in unexpected behavior. For example, result in content being disclosed that actually wanted to prevent with the redirect (HTTP 301). 
Using JavaScript via PHP: 
The windows.location object in JavaScript is used to get the current page address(URL) and to redirect the browser to a new page. The window.location object contains the crucial information about a page such as hostname, href, pathname, port etc.
Example: 

html




<html>
    <head>
        <title>window.location function</title>
    </head>
    <body>
    <p id="demo"></p>
 
    <script>
        document.getElementById("demo").innerHTML =
            "URL: " + window.location.href +"</br>";
        document.getElementById("demo").innerHTML =
        document.getElementById("demo").innerHTML +
        "Hostname: " + window.location.hostname + "</br>";
        document.getElementById("demo").innerHTML =
        document.getElementById("demo").innerHTML +
        "Protocol: " + window.location.protocol + "</br>";
    </script>
    </body>
</html>                   


Output: 

URL: https://ide.geeksforgeeks.org/tryit.php
Hostname: ide.geeksforgeeks.org
Protocol: https:

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.

RELATED ARTICLES

Most Popular

Dominic
32350 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6720 POSTS0 COMMENTS
Nicole Veronica
11882 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6839 POSTS0 COMMENTS
Ted Musemwa
7101 POSTS0 COMMENTS
Thapelo Manthata
6794 POSTS0 COMMENTS
Umr Jansen
6794 POSTS0 COMMENTS