Handling Script Termination after Header Redirection
In PHP, the header() function is used to send HTTP headers to the client. When used for redirection, a common question arises: should you call exit() or return after calling header()?
Consider the following scenario:
<?php $urlFailToGoTo = '/formerror.php'; if (sth) { header(sprintf("Location: %s", $urlFailToGoTo)); exit(); // Should I call exit() here? } ?>
After sending the redirect header, the script execution continues unless explicitly terminated. To ensure immediate redirection, it is recommended to call exit() after header(). This prevents the execution of any последующий code that could potentially interfere with the redirect.
Why exit() is Preferable
While both exit() and return can terminate script execution, exit() has a few advantages:
Therefore, the best practice is to call exit() immediately after calling header() to ensure a clean and immediate redirection.
The above is the detailed content of Should I Use `exit()` or `return` After a PHP `header()` Redirect?. For more information, please follow other related articles on the PHP Chinese website!