在输出用户消息后重定向PHP页面

问题描述 投票:5回答:4

我试图在成功执行后重定向页面。但是,我想在重定向完成时向用户显示一条消息(例如“Changed made。重定向...”)。在页面输出后更改header变量会导致PHP出错,我知道这一点。我的问题是,我该怎么做?

我目前的代码是这样的

// ... execution code
echo 'Changes made successfully. Now redirecting...';
header('Location: index.php');

这不起作用。我也看到了SO的答案,建议我分别在页面的开头和结尾使用ob_start()ob_flush()。但这也没有解决我的问题,我仍然得到错误。

NB我只需要使用PHP,我不希望JavaScript用于重定向。

编辑:我最终使用JavaScript进行重定向,因为我需要在重定向之前向用户输出一些有用的消息,而单独使用PHP并不是最好的解决方案。

php redirect header output
4个回答
2
投票

首先,你不能在回声或任何输出后使用“标题”。第二,为什么你需要PHP呢?你可以使用javascript或最好的,只需把它放在html就像它说here


1
投票

设置标题后回显。

header("refresh:1;url=test.php"); 
echo 'this is a test';
exit;

0
投票
header( "refresh:5;url=wherever.php" );

您可以在5秒后将页面重定向到wherever.php。请看这个问题:Page redirect after certain time PHP


0
投票

通过所有三种流行方法的重定向缺点

 header('Location:$url'); 
 echo "<meta http-equiv='refresh' content='3;$url>";
 echo "<body onload='window.location=$url'>";

是您需要在向用户显示页面的任何部分之前决定可能的重定向。当决策过程耗时时,用户将在空白页面上大喊大叫。我使用Javascript OnLoad事件的延迟重定向,该事件在页面顶部声明,但只有当ID体'重定向'的隐藏对象稍后在HTML正文中的任何地方回显时才会执行实际重定向。

echo "<html><body onload='if (typeof(Redirect)!=undefined) 
setTimeout(function()
    {window.location=document.getElementById(\"Redirect\").value},3000);'>";
echo $HtmlBody; echo $FormToFill;flush();
if (CheckReceivedDataFailed()) echo "Wrong data, please fill the form again";
else echo "<input type='hidden' id='Redirect' value='$url'>
           Thanks, youll be redirected in 3 sec";
echo "</body></html>";
© www.soinside.com 2019 - 2024. All rights reserved.