Home  >  Article  >  Backend Development  >  How to redirect in PHP

How to redirect in PHP

青灯夜游
青灯夜游Original
2019-01-18 17:47:225700browse

Redirection from one page to another page in PHP is usually implemented using the header() function or JavaScript code. This article will introduce to you how to use these two methods for redirection. I hope it will be helpful to you.

How to redirect in PHP

Use the header() function in PHP for redirection

header() function is a built-in function in PHP that is used to send raw HTTP (Hypertext Transfer Protocol) headers to the client.

Basic sentence pattern:

header( $header, $replace, $http_response_code )

$header: This parameter is used to save the header string.

$replace: This parameter is used to hold the replace parameter, which indicates that the header should replace a previous similar header, or add a second header of the same type. It is an optional parameter.

$http_response_code: This parameter saves the HTTP response code.

Code example:

<?php
// 重定向浏览器
header("Location: http://www.php.cn"); 
exit; 
?>

Note: The exit or die function after the header() function is required.

Using JavaScript code through PHP

In JavaScript, you can use the windows.location object for redirection, which can be used to get the current page address (URL) and redirect the browser to a new page. The window.location object contains important information about the page, such as hostname, href, pathname, port, etc.

Code sample:

<?php
// 在PHP中使用javascript,实现重定向浏览器
echo &#39;<script type="text/JavaScript"> &#39;;
  
echo "window.location.href= &#39;http://www.php.cn&#39;;";
echo  "</script>";
?>

Recommended related articles: How to run JavaScript code in PHP? (Code example)

The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !

The above is the detailed content of How to redirect in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn