3

我正在使用以下函数在特定任务后重定向一个人(例如:登录后、注销后、搜索后等)代码如下:

<?php
class common {
    /* Redirect to another page
     * $url= Url to go
    */
    function redirection($url){
        header("location: $url");
        exit();
    }
    // Some other function below
?>

但现在我正在处理这个类与不同主机的许多项目(传销项目)。我现在有个问题。对于某些服务器,它可以按我的预期工作,但在其他一些服务器中,它不会重定向。如果我启用error_reporting(E_ALL);我发现了一个通知headers are already send。所以我很困惑我现在能做什么而不是header()功能。我也尝试了下面的代码

<?php
    function redirection($url){
        echo "<div align='center'><a href='$url' target='_top'><img src='../img/proceed.jpg' alt='Proceed>>' align='absmiddle' border='0'></a></div>";
        exit();
    }
?>

但这是不可取的,因为每个人都希望自动重定向。我的服务器都是windows和linux。请帮助我任何人

4

5 回答 5

3

好吧,这种情况很常见,那么你可以简单地打开输出缓冲(输出将存储在内部缓冲区中)。

ob_start();在应用程序的第一行使用

<?php
    class common {

        /* Redirect to another page
         * $url= Url to go
         */

        function redirection($url)
        {
          header("location: $url");
          exit();
        }

        // Some other function below

    }

?>


<?php
    ob_start("redirection");

    // Your Common Class Page
    include("Common.php");

     // some code 

    ob_end_flush(); // turn off output buffering
?>
于 2011-09-17T17:00:39.830 回答
1

处理这个问题的一种方法是在调用 header(location) 之前测试 header 是否已经发送。您可以混合使用两种解决方案:

<?php
class common {
    /* Redirect to another page
     * $url= Url to go
    */
    function redirection($url){
        if (!headers_sent()) {
            header("location: $url");
        } else {
            echo "<div align='center'><a href='$url' target='_top'><img src='../img/proceed.jpg' alt='Proceed>>' align='absmiddle' border='0'></a></div>";
        }
        exit();
    }
// Some other function below
?>

这样,如果标头尚未发送,您将自动重定向。如果他们有,您要求客户点击。

这就是为什么当你在大多数网站上看到重定向通知时,它还包括一句话说明——如果你没有被自动重定向,请点击这里...

希望这可以帮助。

祝你好运!

于 2011-09-17T16:55:54.613 回答
0

我会尝试使用:

header("Location: ".$url, TRUE, 302);

如果你想使用不同的方法,或者叫做“刷新”的方法,

header("Refresh:0;url=".$url);

两者都适用于任何情况。您的标头的问题是,您需要让他们知道这是一个 302 重定向,并设置TRUE以替换现有的标头。如果 header 已经设置,您需要使用TRUE布尔值替换它。

302 也是常见的 HTTP 重定向响应码,在尝试使用 header 重定向时需要指定。

Refresh 方法也可以正常工作,尽管它与旧版浏览器存在兼容性问题。

http://en.wikipedia.org/wiki/HTTP_302

http://php.net/manual/en/function.header.php

于 2011-09-17T16:53:08.423 回答
0

如果标头已经发送,很可能是因为内容已经写到屏幕上(通过回显、打印或类似方式)。由于您的类无法控制在实例化和调用函数之前发生了什么,因此您似乎不太可能做很多事情来避免您的客户端 PHP(调用您的类)之前写出任何东西。使用 Javascript 或使用Apache 重定向

于 2011-09-17T16:53:30.330 回答
-2

最简单的方法是通过客户端来完成。javascript...

window.location= url
于 2011-09-17T16:51:33.947 回答