Redirect with arguments php

php redirect – How to, Examples, Issues & Solutions

php redirect is a convenient way to redirect https requests to another page. Learn about correct syntax, response code , common errors using session data and time delayed redirection.

php redirect to another page on same or different website is handled by php headers. php header() sends a raw HTTP header which is used to redirect php pages to other locations along with several other function

php header syntax :

header ( string $header [, bool $replace = TRUE [, int $http_response_code ]] ) : void

header is the header string which is ‘Location:’ for php redirect and it sends headers back to browser.

replace parameter is TRUE by default, but can be FALSE if you want to send multiple headers and don’t want to replace send header with first.

response code – default response code is 302,

browsers and search engines treat these response code differently, search engines take a 301 as permanent move to new page and update page rank, this can help in maintaining same search ranking for the page. Browsers use 30x code to determine how long or what to cache for these pages. It makes sense to specify the status code explicitly for php redirects depending on the requirements.

Setting up php redirect header

A php header redirect can be setup as in following example with default parameters.

or by specifying custom parameters

header(“Location: http://example.com”,TRUE,301);
exit;
?>

The url can be relative to the root domain if it is being redirected to same site

the exit function after the redirect is to ensure the further execution of php script stops and exists.

Relative urls in php redirect

The redirect urls can be constructed using php environment variables as in following example:

$url = ‘http://’ . $_SERVER[‘HTTP_HOST’]; // Get server
$url .= rtrim(dirname($_SERVER[‘PHP_SELF’]), ‘/\\’); // Get current directory
$url .= ‘/relative/path/to/page/’; // relative path
header(‘Location: ‘ . $url, TRUE, 302);

php redirect using session data

session data can be used to redirect based on valid user credentials. However care needs to be taken that search bots and other bots may not looks at the session data and may end up fetching your pages.

Читайте также:  The best editor html

if (!isset( $_SESSION[“authorized-user”]))
header(“location. /”);
exit();
>

Header already sent error in php redirect

This is very common error and sometime difficult to debug. The root cause of this error is that php redirect header must be send before anything else. This means any space or characters sent to browser before the headers will result in this error.

Like following example, there should not be any output of even a space before the headers are sent.

Even a Byte Order Mark can cause this issue when the text encoding is utf8-BOM, this can be fixed by saving again with encoding as utf8 without BOM in text editors.

Internal server error in php redirect

The directive Location is sensitive to the placement of colon, The colon : should always be placed next to Location as Location: , any space between Location and : can result in malfunction and internal server error.

This is NOT correct, notice the placement of colon,

Correct way is :

Replace php redirect header

the headers can be replaced with another entry as long as nothing is sent to browsers

header(“location: page1.php”);
header(“location: page2.php”); //replaces page1.php
exit;
?>

In the following example, headers are not replaced as browser follows the first redirect and then prints the message. No header already sent message here as browser has already redirected before coming to second redirect.

header(“location: page1.php”);
echo “moving to page 2”
header(“location: page2.php”); //replaces page1.php
?>

php redirect with time delay

As you can’t send anything before php headers, to delay a redirect and display a message, you will have to user refresh function instead of Location

The following examples redirects to page after 5 seconds and displays a message during the 5 sec. delay.

Redirecting using other methods

following examples avoid headers already sent issues.

1. php redirect using ob_start() and ob_end_flush() php functions

ob_start(), output buffer keeps everything in buffer without sending or displaying until it is flushed

ob_start(); //this has to be the first line of your page
header(‘Location: page2.php’);
ob_end_flush(); //this has to be the last line of your page
?>

2. Redirect using javascript

This simple example does the redirection using javascript.

Источник

How to redirect in PHP

The URL of the user’s browser can be changed from one location to another by using redirection. The redirection is required for many purposes, such as switching from HTTP to HTTPS, changing domain, etc. When the user sends a request for a page to the server that does not exist or of a page location that has changed, then the server will send the information about the new URL with 301 or 302 HTTP code. It will help the user to know about the new URL by redirection, and the user will send a request to the new location to get the desired content. The URL redirects in PHP by using the header() function. How the header() function can be used in PHP to redirect URL from one page to another page is shown in this tutorial.

Читайте также:  Css изменения в силу

header() function

It is a built-in PHP function to send the raw HTTP header to the client. The syntax of this function is shown below.

Syntax:
header( $header, [$replace, [$http_response_code]] )

This function can take three arguments. The first argument is mandatory, and the last two arguments are optional. The $header is used to store the header string that contains the location of the redirection. The $replace defines whether to replace the previous similar header, and the value of this argument is Boolean. The $http_response_code is used to store a specific response code that will send to the user.

Example-1: Redirect URL with default status code

Create a PHP file with the following code that will redirect to the new location after waiting for 2 seconds. Here, the die() function is used to terminate the script. When the header() function is used with one argument, then 302 is used as the default HTTP code.

//Wait for 2 seconds
sleep ( 2 ) ;
//Redirect to the particular location
header ( «Location: http://localhost/php/contactForm/index.html» ) ;
die ( ) ;

Output:
After executing the code, The URL is redirected to the location http://localhost/php/contactForm/index.html after 2 seconds. If you inspect the code and open the Network tab, then it will show 302 as the default status code.

Example-2: Redirect URL permanently

Create a PHP file with the following code that will redirect to the new location after waiting for 2 seconds. Here, the die() function is used to terminate the script. Here, the header() function is used with three arguments. The TRUE is used for the second argument and 301 is used for the third argument. The 301 status code is used to redirect permanently.

//Wait for 2 seconds
sleep ( 2 ) ;
//Redirect to the particular location
header ( «Location: http://localhost/php/contactForm/index.html» , TRUE , 301 ) ;
die ( ) ;

Output:
After executing the code, The URL is redirected to the location http://localhost/php/contactForm/index.html after 2 seconds. If you inspect the code and open the Network tab, then it will show 301 as a status code that indicates the URL is moved permanently.

Example-3: Redirect URL temporary

Create a PHP file with the following code that will redirect to the new location after waiting for 2 seconds. Here, the die() function is used to terminate the script. Here, the header() function is used with three arguments. The TRUE is used for the second argument and 307 is used for the third argument. The 307 status code is used to redirect temporarily.

//Wait for 2 seconds
sleep ( 2 ) ;
//Redirect to the particular location
header ( «Location: http://localhost/php/contactForm/index.html» , TRUE , 307 ) ;
die ( ) ;

Читайте также:  Interactive plots with python

Output:
After executing the code, The URL is redirected to the location http://localhost/php/contactForm/index.html after 2 seconds. If you inspect the code and open the Network tab, then it will show 307 as a status code that indicates the URL is redirected temporarily.

Example-4: Redirect URL based on the condition

Create a PHP file with the following code that will redirect the URL based on the conditional statement. An HTML form is designed in the script to redirect URL based on the selected value of the drop-down list. Here, the drop-down list contains three values. When Google is selected from the drop-down list then the PHP script will redirect the URL to the location https://google.com with the default status code, 302. When LinuxHint is selected from the drop-down list then the PHP script will redirect the URL to the location https://linuxhint.com with the status code 301. When Fahmidasclassroom is selected from the drop-down list, then the PHP script will redirect the URL to the location, https://fahmidasclassroom.com with the status code, 302.

//Check the submit button is pressed or not
if ( isset ( $_POST [ «submit» ] ) )
{
if ( $_POST [ ‘web’ ] == ‘Google’ )
{
//Redirect to the particular location
header ( «Location: https://google.com» ) ;
}
elseif ( $_POST [ ‘web’ ] == ‘LinuxHint’ )
{
//Redirect to the particular location
header ( «Location: https://linuxhint.com» , TRUE , 301 ) ;
}
else
{
//Redirect to the particular location
header ( «Location: https://fahmidasclassroom.com» ) ;
}
die ( ) ;
}

Output:
After executing the code, the following output will appear in the browser that will display a drop-down list with three values and a Go button. The status code is 200 now. After redirection, the status code will be changed.

If Google will select from the drop-down, then it will redirect to the location https://google.com after pressing the Go button, and the following image will appear. The default status code, 302, is generated here.

If the LinuxHint selects from the drop-down, then it will redirect to the location https://linuxhint.com after pressing the Go button, and the following image will appear. The permanent status code, 301, is generated here.

Conclusion:

The different uses of the PHP header() function are explained in this tutorial by using multiple examples. The redirection can be done temporarily and permanently based on the status code used in the header() function. This tutorial will help the readers know more about the purpose of redirection and apply it by using PHP script in their web application when required.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Оцените статью