是否可以通过使用PHP将用户重定向到不同的页面?
假设用户转到www.example.com/page.php,我想将其重定向到www.example.com/index.php,那么在不使用元刷新的情况下,我如何做到这一点?有可能吗?
这甚至可以保护我的页面免受未授权用户的攻击。
是否可以通过使用PHP将用户重定向到不同的页面?
假设用户转到www.example.com/page.php,我想将其重定向到www.example.com/index.php,那么在不使用元刷新的情况下,我如何做到这一点?有可能吗?
这甚至可以保护我的页面免受未授权用户的攻击。
当前回答
我已经回答了这个问题,但我会再回答一次,因为在此期间我了解到,如果您在CLI中运行(重定向无法发生,因此不应该exit()),或者您的Web服务器以(F)CGI的形式运行PHP(它需要预先设置的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)
其他回答
header('位置:http://www.yoursite.com/new_page.html' );
Use:
<?php header('Location: another-php-file.php'); exit(); ?>
或者,如果您已经打开了PHP标记,请使用以下命令:
header('Location: another-php-file.php'); exit();
您还可以重定向到外部页面,例如:
header('Location: https://www.google.com'); exit();
确保包含exit()或includedie()。
1.不带收割台
在这里你不会遇到任何问题
<?php echo "<script>location.href='target-page.php';</script>"; ?>
2.使用带有exit()的头函数
<?php
header('Location: target-page.php');
exit();
?>
但是如果你使用header函数,有时你会得到“警告”likeheader already send”来解析在发送头之前不回显或打印的问题,或者您可以在头函数之后简单地使用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
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>
使用header()函数发送HTTP位置标头:
header('Location: '.$newURL);
与一些人的想法相反,die()与重定向无关。仅当您希望重定向而不是正常执行时使用它。
文件example.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
恢复-强制性die()/exit()是一些与实际PHP无关的都市传说。这与客户端“尊重”Location:标头无关。无论使用何种客户端,发送头都不会停止PHP执行。