是否可以通过使用PHP将用户重定向到不同的页面?

假设用户转到www.example.com/page.php,我想将其重定向到www.example.com/index.php,那么在不使用元刷新的情况下,我如何做到这一点?有可能吗?

这甚至可以保护我的页面免受未授权用户的攻击。


当前回答

Use:

<?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.
?>

其他回答

使用echo从PHP输出JavaScript,这将完成任务。

echo '<script type="text/javascript">
           window.location = "http://www.google.com/"
      </script>';

除非缓冲页面输出,然后稍后检查重定向条件,否则在PHP中无法真正做到这一点。这可能太麻烦了。记住,头是从页面发送的第一件事。大多数重定向通常需要在页面的后面进行。为此,您必须缓冲页面的所有输出,并在稍后检查重定向条件。此时,您可以重定向页面用户header()或简单地回显缓冲的输出。

有关缓冲的更多信息(优点)

什么是输出缓冲?

试试这个

 $url = $_SERVER['HTTP_REFERER'];
 redirect($url);

在语义网络的前夜,正确性是需要考虑的问题。不幸的是,PHP的“Location”标头仍然使用HTTP302重定向代码,严格来说,这不是最佳的重定向代码。它应该使用的是303。

W3C很高兴地提到,303标头与“许多HTTP/1.1之前的用户代理”不兼容,这相当于当前使用的浏览器。因此,302是一件遗物,不应该使用。

…或者你可以像其他人一样忽略它。。。

用PHP重定向的最佳方法是以下代码。。。

 header("Location: /index.php");

确保没有代码在

header("Location: /index.php");

所有代码必须在上述行之前执行。

认为

案例1:

echo "I am a web developer";
header("Location: /index.php");

它将正确重定向到该位置(index.php)。

案例2:

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();
?>

但是如果你使用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
?>