How to redirect in php: what you need to know

The URL of the user’s browser can be changed from one location lớn another by using redirection. The redirection is required for many purposes, such as switching from HTTP lớn HTTPS, changing domain, etc. When the user sends a request for a page khổng lồ the hệ thống that does not exist or of a page location that has changed, then the hệ thống will send the information about the new URL with 301 or 302 HTTP code. It will help the user khổng lồ know about the new URL by redirection, & the user will send a request to lớn 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 lớn redirect URL from one page lớn another page is shown in this tutorial.

header() function

It is a built-in PHP function khổng lồ send the raw HTTP header khổng lồ the client. The syntax of this function is shown below.

Bạn đang xem: How to redirect in php: what you need to know

Syntax:header( $header, <$replace, <$http_response_code>> )

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

Example-1: Redirect URL with mặc định status code

Create a PHP tệp tin with the following code that will redirect to lớn the new location after waiting for 2 seconds. Here, the die() function is used to lớn terminate the script. When the header() function is used with one argument, then 302 is used as the mặc định HTTP code.

Xem thêm: Progressive Web App Hay Pwa Là Gì ? Cách Xây Dựng 1 Pwa Cho Website


//Wait for 2 secondssleep(2);//Redirect to lớn the particular locationheader("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 mở cửa the Network tab, then it will show 302 as the mặc định status code.

*
*
*
*
*
*
*

Conclusion:

The different uses of the PHP header() function are explained in this tutorial by using multiple examples. The redirection can be done temporarily & 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.