Home >Backend Development >PHP Tutorial >Should You Use `exit()` After a `Location:` Header in PHP?
Should exit() Be Used After Location: header?
After invoking the header function for redirection, it's crucial to decide whether to call exit() or not. This question arises because header does not automatically end script execution.
Why Call exit()?
Using exit() after header is highly recommended for the following reasons:
Example Usage:
As shown in the given example, exit() should be called immediately after setting the Location header:
<?php // fileA $urlFailToGoTo = '/formerror.php'; if (sth) { header(sprintf("Location: %s", $urlFailToGoTo)); exit(); }
Avoid Using return:
Using return in place of exit() here is incorrect. return normally ends a function or method, but in this case, the script is a standalone program that doesn't return to any caller. exit() is the appropriate choice for terminating script execution cleanly.
The above is the detailed content of Should You Use `exit()` After a `Location:` Header in PHP?. For more information, please follow other related articles on the PHP Chinese website!