I'm creating a script to validate a form and I was asking myself a question. When I use a header (see example below), do I need to use exit right after? I mean, does using header also means that it is exiting by default therefore I don't need to use the command exit?
// cancel button clicked
if (isset($_POST['cancel'])) {
header("Location: http://localhost/admin/tracks.php");
exit;
}
echo '<p>$name</p>'
You should call exit()
because a header()
won't automatically stop the script from executing - or if it does (I'm honestly not 100% on that), it definitely doesn't stop the script instantly.
For example, try this code:
<?php
header("Location: http://www.google.com");
unlink(__FILE__);
?>
This little script uses header()
to redirect you to Google, and then deletes itself. If you run it, you'll notice that after you were redirected, the file was still deleted. This means that the unlink()
call was still executed even though the header()
call redirected you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With