cohen
cohen

Reputation: 621

what is php exit doing in function?

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?

Upvotes: 3

Views: 4398

Answers (4)

JohannesAndersson
JohannesAndersson

Reputation: 4620

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

Upvotes: 0

ChocoDeveloper
ChocoDeveloper

Reputation: 14568

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

Upvotes: 4

Andr&#233; Catita
Andr&#233; Catita

Reputation: 1323

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.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

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.

Upvotes: 7

Related Questions