Redirect in php function

How to Redirect a Web Page with PHP

This short snippet will show you multiple ways of redirecting a web page with PHP.

So, you can achieve redirection in PHP by following the guidelines below.

Using the header() Function

This is an inbuilt PHP function that is used for sending a raw HTTP header towards the client.

The syntax of the header() function is as follows:

header( $header, $replace, $http_response_code )

Also, it is likely to apply this function for sending a new HTTP header, but one should send it to the browser prior to any text or HTML.

Let’s see how to redirect a web page using the header() function:

 header('Location: //www.w3docs.com'); // or die(); exit(); ?>

As you can notice, exit() is used in the example above. It is applied to prevent the page from showing up the content remained (for instance, prohibited pages).

Also, you can use the header() function with ob_start() and ob_end_flush() , like this:

 ob_start(); //this should be first line of your page header('Location: target-page.php'); ob_end_flush(); //this should be last line of your page

Using a Helper Function

Here, we will demonstrate how to use a helper function for redirecting a web page. Here is an example:

 function Redirect($url, $permanent = false) < header('Location: ' . $url, true, $permanent ? 301 : 302); exit(); > Redirect('//www.w3docs.com/', false);

All HTTP status codes are listed at HTTP Status Messages

Note that this function doesn’t support 303 status code!

Let’s check out a more flexible example:

 function redirect($url, $statusCode = 303) < header('Location: ' . $url, true, $statusCode); die(); >

In some circumstances, while running in CLI (redirection won’t take place) or when the webserver is running PHP as a (F) CGI, a previously set Statusheader should be set to redirect accurately.

 function Redirect($url, $code = 302) < if (strncmp('cli', PHP_SAPI, 3) !== 0) < if (headers_sent() !== true) < if (strlen(session_id()) > 0) < // if using sessions session_regenerate_id(true); // avoids session fixation attacks session_write_close(); // avoids having sessions lock other requests > if (strncmp('cgi', PHP_SAPI, 3) === 0) < header(sprintf('Status: %03u', $code), true, $code); > header('Location: ' . $url, true, preg_match('~^30[1237]$~', $code) > 0 ? $code : 302); > exit(); > > ?>

JavaScript via PHP

Here, we will provide you with an alternative method of redirection implementing JavaScript via PHP. In JavaScript, there is a windows.location object that is implemented for getting the current URL and redirecting the browser towards a new webpage. This object encompasses essential information about a page (for example, href, a hostname, and so on).

This is how to redirect a web page using window.location:

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

To conclude, let’s assume that in this short tutorial, we provided you with multiple methods to redirect a web page with PHP. Also, you can find information on how to redirect web pages with HTML, JavaScript, Apache and Node.js.

Источник

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.

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 ( ) ;

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.

Источник

Как сделать редирект PHP

Как сделать редирект PHP

На страницах сайтов постоянно что-то добавляется, удаляется и обновляется, чтобы в поисковиках была только актуальная информация и нужные страницы не выпадали из поиска применяются редиректы. Также редиректы используются после отправки форм чтобы не было возможности отправить форму несколько раз.

  • 301 – текущая страница удалена на всегда, заменой старой считать новый URL.
  • 302 – текущая страница временно не доступна, заменой считать пока новый URL.
  • 303 – используется после отправки формы методом POST (подробнее Post/Redirect/Get — PRG).

Итак, сделать 301-й редирект можно так:

header('Location: https://example.com', true, 301); exit();

Но функция header() не сработает если до ее вызова в браузер уже выводился какой-то контент и вызовет ошибку:

Warning: Cannot modify header information — headers already sent by…

Исправить ее можно использовав буферизацию вывода добавив в самое начало скрипта ob_start() ;

Также можно подстраховаться добавив JS-редирект и ссылку если функция header() не сработает.

Упростить использование кода можно выделив его в отдельную функцию:

function redirect($url, $code = 301) < header('Location: ' . $url, true, $code); echo ""; echo 'Перенаправление… Перейдите по ссылке.'; exit(); > /* В index.php */ if ($_SERVER['REQUEST_URI'] == '/url-old') < redirect('https://example.com/url-new'); >
$urls = array( array('/url-old-1', 'https://example.com/url-new-1'), array('/url-old-2', 'https://example.com/url-new-2'), array('/url-old-3', 'https://example.com/url-new-3'), ); foreach ($urls as $row) < if ($_SERVER['REQUEST_URI'] == $row[0]) < redirect($row[1]); >>

Источник

Читайте также:  Фоновый цвет html css
Оцените статью