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

Php

Php Problem Overview


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

Php Solutions


Solution 1 - Php

You definitely should. Otherwise the script execution is not terminated. Setting another header alone is not enough to redirect.

Solution 2 - Php

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.

Solution 3 - Php

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.

Solution 4 - Php

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

Solution 5 - Php

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 ...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionq0987View Question on Stackoverflow
Solution 1 - PhprgroliView Answer on Stackoverflow
Solution 2 - PhpJan TuroňView Answer on Stackoverflow
Solution 3 - PhpAmberView Answer on Stackoverflow
Solution 4 - PhpHydrinoView Answer on Stackoverflow
Solution 5 - PhpBenjamin EcksteinView Answer on Stackoverflow