How do I navigate to another page when PHP script is done?

108,215
if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}
Share:
108,215
nkcmr
Author by

nkcmr

Updated on January 22, 2021

Comments

  • nkcmr
    nkcmr over 3 years

    I have a simple POST script that I need to return to the page that was doing the Posting.

    Is there any way to do it like this?

    if($done)
        {
            //go to page
        }
    
  • Sarwar Erfan
    Sarwar Erfan over 13 years
    Make sure you do NOT output anything before this. If you output anything, this wont work.
  • phooji
    phooji over 13 years
    I can't seem to comment on Jordan's answer, so here is my comment as a separate answer. Jordan's approach will work, but you cannot include any echo, print, or plain HTML before you put the call to header. In general, this means that you should put your 'should I redirect' logic above any output. This makes sense -- why send data for a webpage if you're just going to redirect anyway? If you absolutely have to, though, you can use output buffering to try to get around this restriction.
  • Brad Christie
    Brad Christie over 13 years
    @Sarwar: or you could enable output buffering ;-) (though I feel just adhering to the "don't output anything before this line" makes more sense myself)
  • Admin
    Admin over 13 years
    technically you should use the full url, not the relative one, but i have never seen relative fail
  • user3167101
    user3167101 over 13 years
    @Dagon Why should you use the full URL?
  • Admin
    Admin over 13 years
    @alex because the manual says so :-), see the note in the manual page for header()
  • nkcmr
    nkcmr over 13 years
    Thanks for the heads up, but its just a bunch of MySQL queries before the logic.
  • phooji
    phooji over 13 years
    Keep in mind that error traces may also prevent the redirect from happening (e.g., in case one of your queries fails).