Redirect PHP page AFTER outputting user message

Deadly 提交于 2020-01-24 05:13:10

问题


I am trying to redirect a page after successful execution. However, I want to display a message to the user (e.g. 'Changed made. Redirecting...') while the redirection is done. Changing header variables after output in the page causes errors in PHP and I know this. My question is, how should I do this?

My current code is something like

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

and this doesn't work. I have also seen an answer on SO suggesting I use ob_start() and ob_flush() at the start and end of my page, respectively. But that didn't solve my problem either, I still get the error.

NB I need to use PHP only, I don't want JavaScript for redirection.

Edit: I ended up using JavaScript for redirection, as I needed to output some useful message to the user before redirecting, and PHP alone isn't the best solution for that.


回答1:


first, you cant use "header" after echo or any output. second, why you need php for it? you can use javascript or best, just put it in the html like it says here




回答2:


Echo after setting the header.

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



回答3:


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

You can redirect the page after 5 seconds to wherever.php. Please see this question: Page redirect after certain time PHP




回答4:


Drawback of redirection by all three popular methods

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

is that you need to decide about possible redirection before any part of the page is displayed to user. When the decision process is time consuming, user will gawp at blank page. I use deferred redirection with Javascript OnLoad event, which is declared at the top of page but it does the actual redirection only if a hidden object with id='Redirect' is echoed anywhere later in the HTML body.

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>";


来源:https://stackoverflow.com/questions/16131707/redirect-php-page-after-outputting-user-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!