3

Hi I have this function

function fail($pub, $pvt = '')
{
    global $debug;
    $msg = $pub;
    if ($debug && $pvt !== '')
        $msg .= ": $pvt";

    $_SESSION['msg'] = $msg;
    header ("Location: /voting/"); 
    exit;
}

The page should redirect before it gets to the exit command right? Without the exit command however the function doesn't work correctly (it continues on even though it should have redirected). If anyones knows could you explain why the code continues on if the function did not exit even though in both cases it will redirect?

2
  • DO you have a warning or anything displayed on screen when you remove exit? When you leave it ? Commented Jul 5, 2012 at 8:06
  • exit() is always required if you want to stop the script, and/or redirect the page. Commented Jul 5, 2012 at 8:10

4 Answers 4

7

The browser won't redirect until it receives the whole response after the script ends, and the PHP script certainly doesn't stop when the browser redirects, so ending the script when the browser is supposed to redirect is the best course of action.

Sign up to request clarification or add additional context in comments.

1 Comment

After header function it's always good practice to terminate the rest with exit or die.
4

The 'header' function adds a header to the final output that will be sent to the browser, so the redirect actually happens on the client side. That's why you can keep executing code before the 'redirect'. The 'exit' construct (not function) is there to avoid that.

From the php documentation:

<?php
header("Location: http://www.example.com/"); /* Redirect browser */

/* Make sure that code below does not get executed when we redirect. */
exit;
?>

Comments

0

Yes, however it's crucial you do the exit.

As the rest of the page can be forced to be shown, if someone simply chooses to ignore the header response from that file, that exit just makes sure there's nothing else after it, otherwise the .php would still process the rest of the page, and output whatever there is afterwards.

exit; is an alias for die(), which terminates the execution of the script.

Comments

0

Terminates execution of the script. Shutdown functions and object destructors will always be executed even if exit is called. exit is a language construct and it can be called without parentheses if no status is passed.

$filename = '/path/to/data-file';
$file = fopen($filename, 'r')
    or exit("unable to open file ($filename)");

http://php.net/manual/en/function.exit.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.