提问人:Sam 提问时间:4/20/2009 最后编辑:Paulo BoaventuraSam 更新时间:9/7/2023 访问量:3753908
如何在 PHP 中进行重定向?
How do I make a redirect in PHP?
问:
是否可以通过使用PHP将用户重定向到不同的页面?
假设用户转到并且我想将他们重定向到,如果不使用元刷新,我将如何做到这一点?可能吗?www.example.com/page.php
www.example.com/index.php
这甚至可以保护我的页面免受未经授权的用户的侵害。
答:
使用 header()
函数发送 HTTP Location
标头:
header('Location: '.$newURL);
与某些人的想法相反,与重定向无关。仅当您想要重定向而不是正常执行时才使用它。die()
文件示例.php:
<?php
header('Location: static.html');
$fh = fopen('/tmp/track.txt', 'a');
fwrite($fh, $_SERVER['REMOTE_ADDR'] . ' ' . date('c') . "\n");
fclose($fh);
?>
三次执行的结果:
bart@hal9k:~> cat /tmp/track.txt
127.0.0.1 2009-04-21T09:50:02+02:00
127.0.0.1 2009-04-21T09:50:05+02:00
127.0.0.1 2009-04-21T09:50:08+02:00
恢复 — 强制性 / 是一些都市传说,与实际的 PHP 无关。它与客户端“尊重”标头无关。无论使用何种客户端,发送标头都不会停止 PHP 执行。die()
exit()
Location:
评论
exit()
exit
.htaccess
header( 'Location: http://www.yoursite.com/new_page.html' );
评论
.htaccess
function Redirect($url, $permanent = false)
{
if (headers_sent() === false)
{
header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);
}
exit();
}
Redirect('http://www.google.com/', false);
别忘了 / !die()
exit()
评论
现有答案的摘要加上我自己的两分钱:
1. 基本答案
您可以使用该函数发送新的 HTTP 标头,但必须在任何 HTML 或文本之前(例如,在声明之前)将其发送到浏览器。header()
<!DOCTYPE ...>
header('Location: '.$newURL);
2. 重要细节
die() 或 exit()
header("Location: https://example.com/myOtherPage.php");
die();
为什么你应该使用或 : The Daily WTFdie()
exit()
绝对或相对 URL
自 2014 年 6 月起,可以使用绝对 URL 和相对 URL。请参阅 RFC 7231,它取代了旧的 RFC 2616,其中只允许使用绝对 URL。
状态代码
PHP 的 “Location” 标头仍然使用 HTTP 302 重定向代码,这是一个“临时”重定向,可能不是您应该使用的重定向。您应该考虑 301(永久重定向)或 303(其他)。
注意:W3C 提到 303 标头与“许多 HTTP/1.1 之前的用户代理”不兼容。目前使用的浏览器都是 HTTP/1.1 用户代理。对于许多其他用户代理(如蜘蛛和机器人)来说,情况并非如此。
3. 文档
HTTP 标头和 PHP 中的函数header()
4. 替代方案
您可以使用需要安装 PECL 软件包 pecl 的替代方法。http_redirect($url);
5. 辅助函数
此函数不包含 303 状态代码:
function Redirect($url, $permanent = false)
{
header('Location: ' . $url, true, $permanent ? 301 : 302);
exit();
}
Redirect('https://example.com/', false);
这更灵活:
function redirect($url, $statusCode = 303)
{
header('Location: ' . $url, true, $statusCode);
die();
}
6. 解决方法
如前所述,重定向仅在写出任何内容之前起作用。如果在 HTML 输出中调用,它们通常会失败。然后,您可以使用 HTML 标头解决方法(不是很专业!),例如:header()
<meta http-equiv="refresh" content="0;url=finalpage.html">
甚至是 JavaScript 重定向。
window.location.replace("https://example.com/");
评论
header('Location: '.$newURL);
http-equiv="Location"
refresh
<meta http-equiv="refresh" content="0;url=http://example.com/">
就像这里的其他人说的那样,发送位置标头:
header( "Location: http://www.mywebsite.com/otherpage.php" );
但是您需要在将任何其他输出发送到浏览器之前执行此操作。
此外,如果您打算使用它来阻止未经身份验证的用户访问某些页面,就像您提到的,请记住,某些用户代理会忽略这一点并继续访问当前页面,因此您需要在发送后 die()。
评论
but you need to do it before you've sent any other output to the browser.
棒!!几分钟来一直在寻找为什么我一直收到已发送的标头错误。+1!!
die()
这些答案中的大多数都忘记了非常重要的一步!
header("Location: myOtherPage.php");
die();
把那重要的第二行排除在外,可能会让你最终登上 The Daily WTF。问题在于浏览器不必尊重页面返回的标题,因此在标题被忽略的情况下,页面的其余部分将在没有重定向的情况下执行。
评论
die();
在语义网的前夕,正确性是需要考虑的事情。不幸的是,PHP 的 “Location” 标头仍然使用 HTTP 302 重定向代码,严格来说,这并不是重定向的最佳代码。它应该改用的是 303 那个。
W3C 善意地提到,303 标头与“许多 HTTP/1.1 之前的用户代理”不兼容,这相当于当前使用的浏览器。所以,302是遗物,不应该使用。
...或者你可以像其他人一样忽略它......
我已经回答了这个问题,但我会再做一次,因为与此同时,我了解到,如果您在 CLI 中运行(重定向不会发生,因此不应该发生),或者如果您的 Web 服务器将 PHP 作为 (F)CGI 运行(它需要先前设置的标头才能正确重定向),则存在特殊情况。exit()
Status
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();
}
}
我还处理了支持不同HTTP重定向代码(、和)的问题,这在我之前的回答的评论中得到了解决。以下是说明:301
302
303
307
- 301 - 永久移动
- 302 - 已找到
- 303 - 查看其他
- 307 - 临时重定向 (HTTP/1.1)
其中许多答案都是正确的,但它们假设您有一个绝对 URL,但事实可能并非如此。如果你想使用一个相对的URL并生成其余的,那么你可以做这样的事情......
$url = 'http://' . $_SERVER['HTTP_HOST']; // Get the server
$url .= rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // Get the current directory
$url .= '/your-relative/path-goes/here/'; // <-- Your relative path
header('Location: ' . $url, true, 302); // Use either 301 or 302
使用 echo 从 PHP 输出 JavaScript,这将完成这项工作。
echo '<script type="text/javascript">
window.location = "http://www.google.com/"
</script>';
除非你缓冲页面输出,然后检查重定向条件,否则你不能在PHP中真正做到这一点。这可能太麻烦了。请记住,标题是从页面发送的第一件事。大多数重定向通常在页面的后面需要。为此,您必须缓冲页面的所有输出,并在以后检查重定向条件。此时,您可以重定向页面用户 header() 或简单地回显缓冲输出。
有关缓冲(优点)的更多信息,请参阅什么是 PHP 中的输出缓冲?。
评论
使用以下代码:
header("Location: /index.php");
exit(0);
您可以使用一些 JavaScript 方法,如下所示
self.location="http://www.example.com/index.php";
window.location.href="http://www.example.com/index.php";
document.location.href = 'http://www.example.com/index.php';
window.location.replace("http://www.example.com/index.php");
评论
用:
<?php header('Location: another-php-file.php'); exit(); ?>
或者,如果您已经打开了PHP标签,请使用以下命令:
header('Location: another-php-file.php'); exit();
您还可以重定向到外部页面,例如:
header('Location: https://www.google.com'); exit();
请确保包含或包含 .exit()
die()
评论
您还可以使用会话变量来控制对页面的访问并授权有效用户:
<?php
session_start();
if (!isset( $_SESSION["valid_user"]))
{
header("location:../");
exit();
}
// Page goes here
?>
http://php.net/manual/en/reserved.variables.session.php。
最近,我遇到了网络攻击,并决定,我需要知道试图访问管理面板或 Web 应用程序保留部分的用户。
因此,我在文本文件中添加了 IP 地址和用户会话的日志访问权限,因为我不想打扰我的数据库。
您可以尝试使用 PHP 函数进行重定向。您需要设置输出缓冲区,以便浏览器不会向屏幕抛出重定向警告。header
ob_start();
header("Location: " . $website);
ob_end_flush();
评论
以下是我的想法:
恕我直言,重定向传入请求的最佳方法是使用位置标头,这是
<?php
header("Location: /index.php");
?>
一旦执行此语句并发送输出,浏览器将开始重定向用户。但是,请确保在发送标头之前没有任何输出(任何回声/var_dump),否则将导致错误。
虽然这是一种快速而肮脏的方式来实现最初要求的目标,但它最终会变成一场 SEO 灾难,因为这种重定向总是被解释为 301 / 302 重定向,因此搜索引擎将始终将您的索引页面视为重定向页面,而不是登录页面/主页。
因此,它会影响网站的SEO设置。
评论
使用 PHP 重定向的最佳方法是以下代码......
header("Location: /index.php");
确保之后没有代码可以工作
header("Location: /index.php");
所有代码都必须在上面一行之前执行。
假设
案例一:
echo "I am a web developer";
header("Location: /index.php");
它将正确重定向到位置(index.php)。
案例二:
return $something;
header("Location: /index.php");
上面的代码不会重定向到位置(index.php)。
评论
1.无标题
在这里,您不会遇到任何问题
<?php echo "<script>location.href='target-page.php';</script>"; ?>
2.在
exit()
中使用标头函数
<?php
header('Location: target-page.php');
exit();
?>
但是,如果您使用标题功能,那么有时您会收到“警告”
喜欢标头已经发送“来解决在发送标头之前不回显或打印的问题,或者您可以简单地使用或之后标头功能。die()
exit()
3.在
ob_start(
) 和ob_end_flush(
) 中使用标头函数
<?php
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
?>
评论
是的,可以使用 PHP。我们将重定向到另一个页面。
请尝试以下代码:
<?php
header("Location:./"); // Redirect to index file
header("Location:index.php"); // Redirect to index file
header("Location:example.php");
?>
用:
<?php
header('Location: redirectpage.php');
header('Location: redirectpage.php');
exit();
echo "<script>location.href='redirectpage.php';</script>";
?>
这是一个常规和正常的PHP重定向,但您可以通过以下代码在几秒钟内制作一个重定向页面:
<?php
header('refresh:5;url=redirectpage.php '); // Note: here 5 means 5 seconds wait for redirect.
?>
如果您在 Apache 上运行,您还可以使用 .htaccess 进行重定向。
Redirect 301 / http://new-site.com/
用:
<?php
$url = "targetpage"
function redirect$url(){
if (headers_sent()) == false{
echo '<script>window.location.href="' . $url . '";</script>';
}
}
?>
评论
是的,你可以使用 header() 函数,
header("Location: http://www.yourwebsite.com/user.php"); /* Redirect browser */
exit();
最佳做法是在函数之后立即调用 exit() 函数,以避免以下代码执行。header()
根据文档,必须在发送任何实际输出之前调用。header()
我们可以通过两种方式做到这一点:
当用户打开时 https://bskud.com/PINCODE/BIHAR/index.php 然后重定向到 https://bskud.com/PINCODE/BIHAR.php
通过下面的PHP代码
<?php header("Location: https://bskud.com/PINCODE/BIHAR.php"); exit; ?>
将上述代码保存在 https://bskud.com/PINCODE/BIHAR/index.php 中
当任何条件为真时,则重定向到另一个页面:
<?php $myVar = "bskud"; if ($myVar == "bskud") { ?> <script> window.location.href="https://bskud.com"; </script> <?php } else { echo "<b>Check the website name again</b>"; } ?>
评论
header()
有多种方法可以做到这一点,但如果你愿意,我建议使用该函数。php
header()
基本上
$your_target_url = “www.example.com/index.php”;
header(“Location : $your_target_url”);
exit();
如果你想把它提升一个档次,最好在函数中使用它。这样,您就可以在其中添加身份验证和其他检查功能。
让我们通过检查用户的级别来尝试一下。
因此,假设您已将用户的权限级别存储在名为 的会话中。u_auth
在function.php
<?php
function authRedirect($get_auth_level,
$required_level,
$if_fail_link = “www.example.com/index.php”){
if ($get_auth_level != $required_level){
header(location : $if_fail_link);
return false;
exit();
}
else{
return true;
}
}
. . .
然后,您将为要进行身份验证的每个页面调用该函数。
就像在或任何其他页面中一样。page.php
<?php
// page.php
require “function.php”
// Redirects to www.example.com/index.php if the
// user isn’t authentication level 5
authRedirect($_SESSION[‘u_auth’], 5);
// Redirects to www.example.com/index.php if the
// user isn’t authentication level 4
authRedirect($_SESSION[‘u_auth’], 4);
// Redirects to www.someotherplace.com/somepage.php if the
// user isn’t authentication level 2
authRedirect($_SESSION[‘u_auth’], 2, “www.someotherplace.com/somepage.php”);
. . .
引用;
若要将访问者重定向到另一个页面(在条件循环中特别有用),只需使用以下代码:
<?php
header('Location: mypage.php');
?>
在本例中,是要将访问者重定向到的页面的地址。此地址可以是绝对地址,也可以包含以下格式的参数:mypage.php
mypage.php?param1=val1&m2=val2)
相对/绝对路径
在处理相对路径或绝对路径时,最好从服务器的根目录 (DOCUMENT_ROOT) 中选择绝对路径。使用以下格式:
<?php
header('Location: /directory/mypage.php');
?>
如果目标页面位于另一台服务器上,请包含完整的 URL:
<?php
header('Location: http://www.ccm.net/forum/');
?>
HTTP 标头
根据 HTTP 协议,HTTP 标头必须发送任何类型的内容。这意味着在标题之前不应发送任何字符 - 即使是空格!before
临时/永久重定向
默认情况下,上面显示的重定向类型是临时的。这意味着搜索引擎(例如 Google 搜索)在编入索引时不会考虑重定向。
如果要通知搜索引擎页面已永久移动到其他位置,请使用以下代码:
<?
header('Status: 301 Moved Permanently', false, 301);
header('Location: new_address');
?>
例如,此页面包含以下代码:
<?
header('Status: 301 Moved Permanently', false, 301);
header('Location: /pc/imprimante.php3');
exit();
?>
当您单击上面的链接时,您将自动重定向到此页面。此外,它是永久重定向(状态:301 永久移动)。因此,如果您在 Google 中输入第一个 URL,您将自动重定向到第二个重定向链接。
PHP代码的解释
位于 header() 之后的 PHP 代码将由服务器解释,即使访问者移动到重定向中指定的地址也是如此。在大多数情况下,这意味着您需要一种方法来遵循函数的功能,以减少服务器的负载:header()
exit()
<?
header('Status: 301 Moved Permanently', false, 301);
header('Location: address');
exit();
?>
评论
¶
¶
mypage.php?param1=val1¶m2=val2)
1.使用header
,一个内置的PHP函数
a) 不带参数的简单重定向
<?php
header('Location: index.php');
?>
b) 使用 GET 参数重定向
<?php
$id = 2;
header("Location: index.php?id=$id&msg=succesfully redirect");
?>
2. 在 PHP 中使用 JavaScript 重定向
a) 不带参数的简单重定向
<?php
echo "<script>location.href='index.php';</script>";
?>
b) 使用 GET 参数重定向
<?php
$id = 2;
echo "<script>location.href='index.php?id=$id&msg=succesfully redirect';</script>";
?>
评论
试试这个
$url = $_SERVER['HTTP_REFERER'];
redirect($url);
我喜欢计算秒数后的那种重定向
<?php
header("Refresh: 3;url=https://theweek.com.br/índex.php");
使用标头函数进行路由
<?php
header('Location: B.php');
exit();
?>
假设我们想从 A.php 文件路由到 B.php,那么我们必须借助 或 。让我们看一个例子<button>
<a>
<?php
if(isset($_GET['go_to_page_b'])) {
header('Location: B.php');
exit();
}
?>
<p>I am page A</p>
<button name='go_to_page_b'>Page B</button>
B.php
<p> I am Page B</p>
评论
要在 PHP 中使用重定向:
<?php header('Location: URL'); exit; ?>
您可以尝试使用
header('Location:'.$your_url)
更多信息可以参考 PHP 官方文档
header("Location: https://www.example.com/redirect.php");
直接重定向到此链接 https://www.example.com/redirect.php
$redirect = "https://www.example.com/redirect.php";
header("Location: $redirect");
首先获取$redirect值,然后重定向到 [value],例如:https://www.example.com/redirect.php
您可以使用 PHP 中的 header() 函数执行重定向到另一个页面。header() 函数向浏览器发送原始 HTTP 标头,该标头可用于将用户重定向到新页面。下面是一个示例:
<?php
// Redirect to a new page
header("Location: https://www.example.com/newpage.php");
exit;
?>
在此示例中,header() 函数发送一个“Location”标头,其中包含用户将被重定向到的新页面的 URL。exit 语句用于立即结束当前脚本执行并防止任何进一步的输出。
评论
protection from unauthorized users