The HTTP protocol provides the redirection in order to redirect the request to another URL or webpage. The redirection is defined as an HTTP header. The PHP programming language provides the redirection with the header()
function which adds the redirect HTTP header to the response. In this tutorial, we examine how to redirect with PHP in different ways.
header() Function Syntax
The header() function is used to add HTTP headers. The syntax for the header() function for HTTP redirection is as below.
header(LOCATION_HEADER,REPLACE,RESPONSE_CODE)
- LOCATION_HEADER is the Location header information with the URL information.
- REPLACE is a boolean value where the existing location header replacement is set.
- RESPONSE_CODE is returned HTTP response code.
Redirect with Location Header
In the following example, we use header()
function with the Location
HTTP header in order to redirect into the new URL https://www.linuxtect.com
.
<?php
header("Location:https://www.linuxtect.com");
?>
Redirect Using Variable
PHP provides dynamic usage of the redirection by using variables. We can use PHP variables in order to redirect to different URLs.
<?php
$url = "https://www.linuxtect.com";
header("Location:".$url);
?>