q0987
q0987

Reputation: 35982

php - Should I call exit() after calling Location: header?

After calling the redirect function header, should I call exit or not?

<?php // fileA
$urlFailToGoTo = '/formerror.php';

if (sth)
{
   header(sprintf("Location: %s", $urlFailToGoTo));
   exit(); //should I call exit() here? or return?
}

?>

Thank you

Upvotes: 90

Views: 54326

Answers (6)

theking2
theking2

Reputation: 2833

REST

A related but not identical case is when implementing a REST api. In this case the body is supposed to contain XML or JSON (or some other esoteric form) so after a payload is established as an array or object and all appropriate headers were provided this would finalise processing:

header( 'Content-Type: application/json' );
exit(json_encode($payload));

or

header( 'Content-Type: application/xml' );
exit(xmlrpc_encode($payload));

Both would return the payload as body content and stop processing immediately freeing up server resources.

Upvotes: -1

rgroli
rgroli

Reputation: 1379

You definitely should. Setting header alone does not terminate the script execution.

Upvotes: 96

Jan Turoň
Jan Turoň

Reputation: 32912

You should, just like @rgroli explains. If you do not want to bother with brackets, you can also call header() IN exit():

if(sth) exit(header("Location: http://example.com"));

Location header in HTTP/1.1 always requires absolute path see the note here.

Note: This is not a hack, since the exit code is used only if the parameter is integer, while header() produces void (it exits with code=0, normal exit). Look at it as exit_header() function like it should be after Location header.

Upvotes: 40

Benjamin Eckstein
Benjamin Eckstein

Reputation: 894

exit is bad coding.

if you ever develop a big project and want to create PHP Unit Testcases, exit will screw you up.

exit terminates the script and your running test! there is no way to recover the test and tell if it has failed or not ...

organise your code the way, that there is no output and the script ends naturally if you use a redirect ...

Upvotes: 6

pilotstarmedia.com
pilotstarmedia.com

Reputation: 577

If you don't have any code (PHP or HTML) under header, you don't have to.

Upvotes: 9

Amber
Amber

Reputation: 526813

It's generally good practice to exit; (note - it's a keyword, so you don't need the ()) after sending a Location: header, since browsers are supposed to redirect to the new page and so further execution of the current script is usually undesired.

Upvotes: 23

Related Questions