How can I redirect a page from one page to another page using PHP?
You can redirect to a page in PHP using the header
function.
The syntax of the PHP header
function is as follows
header( $header, $replace, $http_response_code )
-
$header
: HTTP header string (Location) -
$replace
: An Optional parameter to replace the similar header (TRUE) -
$http_response_code
: Send a specific response code with the request (301, 302, etc.)
Now here is an example of a PHP redirection. It simply redirects the current page to https://www.example.com
.
<?php
header("Location: https://www.example.com/");
exit();
?>
The exit()
function at the end is important to avoid certain complications. You should use it in your code after redirection. You may also use the die()
function.
Another example that include the HTTP response code
<?php
header("Location: http://www.example.com/", TRUE, 301);
exit();
?>
You may also use the redirection to redirect to a certain file as
<?php
header("Location: http://www.example.com/index.php");
exit();
?>
1 Like
You may use the following code snippet.
function Redirect($url, $permanent = false) {
if (headers_sent() === false) {
header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);
}
exit();
}
Redirect('http://example.com/', false);