使用 header() 函数
这是一个内置的 PHP 函数,用于向客户端发送原始 HTTP 标头。
header() 函数的语法如下:
header( $header, $replace, $http_response_code )
此外,它可能会应用此功能来发送新的 HTTP 标头,但应在任何文本或者 HTML 之前将其发送到浏览器。
让我们看看如何使用 header() 函数重定向网页:
<?php header('Location: //www.onitroad.com'); //or die(); exit(); ?>
如我们所见,上面的示例中使用了 exit()。
它用于防止页面显示剩余的内容(例如,禁止页面)。
此外,我们可以将 header() 函数与 ob_start() 和 ob_end_flush() 一起使用,如下所示:
<?php ob_start(); //这应该是页面的第一行 header('Location: target-page.php'); ob_end_flush(); //这应该是页面的最后一行 ?>
通过 PHP 编写 JavaScript
其中我们将为我们提供另一种通过 PHP 实现 JavaScript 的重定向方法。
在 JavaScript 中,实现了一个 windows.location 对象,用于获取当前 URL 并将浏览器重定向到新网页。
此对象包含有关页面的基本信息(例如,href、主机名等)。
这是使用 window.location 重定向网页的方法:
<!DOCTYPE html> <html> <head> <title>window.location function</title> </head> <body> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "URL: " + window.location.href + "</br>"; document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML + "Hostname: " + window.location.hostname + "</br>"; document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML + "Protocol: " + window.location.protocol + "</br>"; </script> </body> </html>
使用辅助函数
其中我们将演示如何使用辅助函数来重定向网页。
下面是一个例子:
function Redirect($url, $permanent = false) { header('Location: ' . $url, true, $permanent ? 301 : 302); exit(); } Redirect('//www.onitroad.com/', false);
请注意,此功能不支持 303 状态码!
让我们看看一个更灵活的例子:
function redirect($url, $statusCode = 303) { header('Location: ' . $url, true, $statusCode); die(); }
在某些情况下,在 CLI 中运行时(不会发生重定向)或者当 Web 服务器将 PHP 作为 (F) CGI 运行时,应将先前设置的 Statusheader 设置为准确重定向。
下面是一个例子:
function Redirect($url, $code = 302){ if (strncmp('cli', PHP_SAPI, 3) !== 0) { if (headers_sent() !== true) { if (strlen(session_id()) > 0) {//是否使用了会话 session_regenerate_id(true); //避免会话受到攻击 session_write_close(); //避免会话锁定其他请求 } 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(); } }
下面的文章将向我们展示使用 PHP 重定向网页的多种方法。
因此,我们可以按照以下教程在 PHP 中实现重定向。
日期:2020-06-02 22:15:51 来源:oir作者:oir