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

How to redirect in PHP

青灯夜游
Release: 2023-04-04 19:38:01
Original
5802 people have browsed it

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 )
Copy after login

$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; 
?>
Copy after login

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>";
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template