如何在 PHP 中进行重定向?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/768431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I make a redirect in PHP?
提问by Sam
Is it possible to redirect a user to a different page through the use of PHP?
是否可以通过使用 PHP 将用户重定向到不同的页面?
Say the user goes to www.example.com/page.phpand I want to redirect them to www.example.com/index.php, how would I do so without the use of a meta refresh? Is it possible?
假设用户去了www.example.com/page.php,我想将他们重定向到www.example.com/index.php,如果不使用元刷新,我该怎么做?是否可以?
This could even protect my pages from unauthorized users.
这甚至可以保护我的页面免受未经授权的用户的侵害。
回答by markus
Summary of existing answers plus my own two cents:
现有答案的摘要加上我自己的两分钱:
1. Basic answer
1. 基本答案
You can use the header()function to send a new HTTP header, but this must be sent to the browser before any HTML or text (so before the <!DOCTYPE ...>declaration, for example).
您可以使用该header()函数发送新的 HTTP 标头,但这必须在任何 HTML 或文本之前发送到浏览器(<!DOCTYPE ...>例如,在声明之前)。
header('Location: '.$newURL);
2. Important details
2. 重要细节
die()or exit()
死()或退出()
header("Location: http://example.com/myOtherPage.php");
die();
Why you should use die()or exit(): The Daily WTF
为什么你应该使用die()或exit(): The Daily WTF
Absolute or relative URL
绝对或相对 URL
Since June 2014 both absolute and relative URLs can be used. See RFC 7231which had replaced the old RFC 2616, where only absolute URLs were allowed.
自 2014 年 6 月起,可以使用绝对 URL 和相对 URL。请参阅RFC 7231,它取代了旧的RFC 2616,其中只允许使用绝对 URL。
Status Codes
状态代码
PHP's "Location"-header still uses the HTTP 302-redirect code, but this is not the one you should use. You should consider either 301(permanent redirect) or 303(other).
PHP 的“位置”标头仍然使用HTTP 302重定向代码,但这不是您应该使用的代码。您应该考虑301(永久重定向)或303(其他)。
Note: W3C mentionsthat the 303-header is incompatible with "many pre-HTTP/1.1 user agents. Currently used browsers are all HTTP/1.1 user agents. This is not true for many other user agents like spiders and robots.
注意:W3C 提到303-header 与“许多 pre-HTTP/1.1 用户代理不兼容。目前使用的浏览器都是 HTTP/1.1 用户代理。对于许多其他用户代理,如蜘蛛和机器人,情况并非如此。
3. Documentation
3. 文档
HTTP Headers and the header()function in PHP
HTTP 标头和header()PHP 中的函数
4. Alternatives
4. 替代品
You may use the alternative method of http_redirect($url);which needs the PECL package peclto be installed.
您可以使用http_redirect($url);需要安装PECL 包 pecl的替代方法。
5. Helper Functions
5. 辅助功能
This function doesn't incorporate the 303 status code:
此函数不包含 303 状态代码:
function Redirect($url, $permanent = false)
{
header('Location: ' . $url, true, $permanent ? 301 : 302);
exit();
}
Redirect('http://example.com/', false);
This is more flexible:
这更灵活:
function redirect($url, $statusCode = 303)
{
header('Location: ' . $url, true, $statusCode);
die();
}
6. Workaround
6. 解决方法
As mentioned header()redirects only work before anything is written out. They usually fail if invoked inmidst HTMLoutput. Then you might use a HTML header workaround (not very professional!) like:
如前所述,header()重定向仅在写出任何内容之前有效。如果在 HTML输出中调用它们,它们通常会失败。然后您可能会使用 HTML 标头解决方法(不是很专业!),例如:
<meta http-equiv="refresh" content="0;url=finalpage.html">
Or a JavaScript redirect even.
甚至是 JavaScript 重定向。
window.location.replace("http://example.com/");
回答by vartec
Use the header()functionto send an HTTP Locationheader:
使用该header()函数发送HTTPLocation标头:
header('Location: '.$newURL);
Contrary to what some think, die()has nothing to do with redirection. Use it onlyif you want to redirect insteadof normal execution.
与某些人的想法相反,die()与重定向无关。仅当您想重定向而不是正常执行时才使用它。
File example.php:
文件example.php:
<?php
header('Location: static.html');
$fh = fopen('/tmp/track.txt', 'a');
fwrite($fh, $_SERVER['REMOTE_ADDR'] . ' ' . date('c') . "\n");
fclose($fh);
?>
Result of three executions:
三个执行的结果:
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
Resuming — obligatory die()/exit()is some urban legend that has nothing to do with actual PHP. It has nothing to do with client "respecting" the Location:header. Sending a header does not stop PHP execution, regardless of the client used.
恢复 - 强制性die()/exit()是一些与实际 PHP 无关的都市传说。它与客户端“尊重”Location:标题无关。无论使用何种客户端,发送标头都不会停止 PHP 执行。
回答by Alix Axel
function Redirect($url, $permanent = false)
{
if (headers_sent() === false)
{
header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);
}
exit();
}
Redirect('http://www.google.com/', false);
Don't forget to die()/exit()!
不要忘记死()/退出()!
回答by Hammad Khan
Output JavaScript from PHP using echo, which will do the job.
使用 echo 从 PHP 输出 JavaScript,这将完成这项工作。
echo '<script type="text/javascript">
window.location = "http://www.google.com/"
</script>';
You can't really do it in PHP unless you buffer the page output and then later check for redirect condition. That might be too much of a hassle. Remember that headers are the first thing that is sent from the page. Most of the redirect is usually required later in the page. For that you have to buffer all the output of the page and check for redirect condition later. At that point you can either redirect page user header() or simply echo the buffered output.
除非您缓冲页面输出然后检查重定向条件,否则您无法真正在 PHP 中执行此操作。那可能太麻烦了。请记住,标题是从页面发送的第一件事。大多数重定向通常需要在页面的后面。为此,您必须缓冲页面的所有输出并稍后检查重定向条件。此时,您可以重定向页面用户 header() 或简单地回显缓冲输出。
For more about buffering (advantages)
有关缓冲的更多信息(优点)
回答by Juned Ansari
1. Using header function with
exit()
1.使用header函数
exit()
<?php
header('Location: target-page.php');
exit();
?>
but if you use header function then some times you will get "warning
like header already send"to resolve that do not echo or print before sending headers or you can simply use die()or exit()after header function.
但是如果您使用标头功能,那么有时您会收到“像标头已经发送的警告”来解决在发送标头之前不回显或打印的问题,或者您可以简单地使用标头功能die()或exit()在标头功能之后。
2. Without header
2. 没有标题
<?php
echo "<script>location.href='target-page.php';</script>";
?>
here you will not face any problem
在这里你不会遇到任何问题
3. Using header function with
ob_start()andob_end_flush()
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
?>
回答by nickf
Most of these answers are forgetting a veryimportant step!
大多数这些答案都忘记了一个非常重要的步骤!
header("Location: myOtherPage.php");
die();
Leaving that vital second line out might see you end up on The Daily WTF. The problem is that browsers do not haveto respect the headers which your page return, so with headers being ignored, the rest of the page will be executed without a redirect.
离开那条重要的第二行可能会让您最终出现在The Daily WTF 上。问题是,浏览器不具备尊重,你的页面返回,所以用被忽略标题,页面的其余部分将不重定向执行的头。
回答by jake
Use:
用:
<?php header('Location: another-php-file.php'); exit(); ?>
Or if you've already opened PHP tags, use this:
或者,如果您已经打开了 PHP 标签,请使用:
header('Location: another-php-file.php'); exit();
You can also redirect to external pages, e.g.:
您还可以重定向到外部页面,例如:
header('Location: https://www.google.com'); exit();
Make sure you include exit()or include die().
确保包含exit()或包含die().
回答by Asuquo12
You can use session variables to control access to pages and authorize valid users as well:
您可以使用会话变量来控制对页面的访问并授权有效用户:
<?php
session_start();
if (!isset( $_SESSION["valid_user"]))
{
header("location:../");
exit();
}
// Page goes here
?>
http://php.net/manual/en/reserved.variables.session.php.
http://php.net/manual/en/reserved.variables.session.php。
Recently, I got cyber attacks and decided, I needed to know the users trying to access the Admin Panel or reserved part of the web Application.
最近,我遇到了网络攻击并决定,我需要了解尝试访问管理面板或 Web 应用程序保留部分的用户。
So, I added a log access for the IP address and user sessions in a text file, because I don't want to bother my database.
因此,我在文本文件中添加了 IP 地址和用户会话的日志访问权限,因为我不想打扰我的数据库。
回答by Luke
Many of these answers are correct, but they assume you have an absolute URL, which may not be the case. If you want to use a relative URLand generate the rest, then you can do something like this...
这些答案中有许多是正确的,但它们假设您有一个绝对 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
回答by joan16v
Use the following code:
使用以下代码:
header("Location: /index.php");
exit(0);

