Yii 重定向在服务器中无法正常工作



登录后,我尝试根据用户角色将用户重定向到其指定的页面。我尝试了重定向和标头,但两者都在服务器中对我不起作用。

我试过了

$this->redirect('dashboard/profile');  
$this->redirect(array('dashboard/profile'));  
header('Location: dashboard/profile');

我收到此错误

Cannot modify header information - headers already sent by (output started at /home/deheal/public_html/dev/index.php:2) 

这一切都在本地完美运行,但在服务器中却不完美,请帮助我。

提前谢谢。

如果要在页面中间的某个位置使用重定向,则需要确保在重定向之前没有输出到浏览器。您可以使用 ob_start() 函数在将输出发送到浏览器之前缓冲输出,以便在执行重定向之前不发送标头

ob_start() .....starts buffering the output
ob_flush()......flushes out the output that was buffered

URL之前使用 /

$this->redirect('/dashboard/profile');  

文本输出到浏览器后,无法使用header()。由于您的header.php可能包含输出 HTML,因此不能使用 header()。

您可以通过几种方式解决此问题:

if statement移动到标题包含上方(这不起作用,正如您在注释中指出的那样,header.php设置uid session和其他vital stuff)。调用脚本顶部的ob_start()以缓冲输出。

根据您更新的问题,您可以使用window.location而不是header("location:URL")

<?php 
//Php code here
?>
      <script type="text/javascript">
       window.location= 'dashboard/profile';
        </script>
<?php 
//Php code here
?>

您可以通过javascript执行重定向,因为渲染后无法修改标头。但是这个函数可以做到这一点。只需调用它,您将被重定向到您想要的页面。

<?php
function redirect_url($url)
{
?>
<script>
document.title="Loading";
document.getElementsByTagName("body")[0].innerHTML="Please Wait.....";
document.getElementsByTagName("body")[0].innerHTML+='<img src="../../images/loading_2.gif" style="height:20px;width:20px;"/>';
window.location.href="<?php
echo $url;
?>";
</script>
<?php
}
?>

我以前也有同样的问题。它在我的控制器上显示标头错误。

复制控制器中的所有代码,然后创建新文件,粘贴 您的代码并使用相同的名称保存。

它必须有所帮助。

最新更新