douhui3305 2016-10-29 17:47
浏览 35
已采纳

标题重定向冲突混乱

I have read about 25 pages about this issue but no real clarity. More confusion than anything.

I have a redirect function I use below

function RedirectToURL($url){
   return header("Location: {$url}");
   exit();
}

then in my code when I want to redirect.

if (register($email, $username, $password)) {

    set_message('<div class="alert-success" data-closable>
    Account Registered.</div>');

    RedirectToURL("index.php");

}

Now it registers the user but produces the following error,

Warning: Cannot modify header information - headers already sent

I have no white spaces or anything.. I read that redirects cause this issue.

My dilemma is that the posts i have read say using ob_start is a good idea, but i found some posts also that say ob_start is a bad idea. because ob_start will remove the error but the issue will still exist.

So by those post i am confused and not sure the correct way to resolve this.

  • 写回答

1条回答 默认 最新

  • doujiu9172 2016-10-29 18:01
    关注

    If your function set_message() outputs passed parameter, headers already sent. You should not print anything before redirect. If you want to print some message after redirect, you can store it in $_SESSION on some key before redirect and output on the index page if the key exists.

    Also, your exit() is unreachable. Remove return before header().

    function RedirectToURL($url)
    {
       header("Location: {$url}");
       exit();
    }
    
    if (register($email, $username, $password)) {
        set_message('<div class="alert-success" data-closable>Account Registered.</div>');
    
        RedirectToURL("index.php");
    }
    
    function set_message($message)
    {
        $_SESSION['redirect_message'] = $message;
    }
    

    Some block on your index page:

    if (array_key_exists('redirect_message', $_SESSION)) {
        echo $_SESSION['redirect_message'];
        unset($_SESSION['redirect_message']);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端