PHP Build a Basic PHP Website (2018) Enhancing a Form Setting an Error Message Variable

Fedor Zhorin
PRO
Fedor Zhorin
Pro Student 3,940 Points

Why we put an exit() command after redirection with header() command?

In this lesson we change the conditional statement with send() metod. Now it looks like this:

   <?php
       if ($mail->send()) {
           header("location:suggest.php?status=thanks");
           exit;
       }
       $error_mesage = "Mailer Error: " . $mail->ErrorInfo;
    ?>

I can't understand why we add the exit() command after header()? And I'm not even sure that this command ever executes. I try to comment this line but nothing has changed.

So I assume that this is just for improving the readability of the code. But maybe I'm wrong

Ben Payne
Ben Payne
1,464 Points

Hey Fedor - Me again haha. Exit is considered best practice to ensure NO OTHER CODE is run after you redirect. The header is going to send a response to the browser which should halt script execution but I have had it where a slow network can actually cause the script to continue to execute, so better to be safe and just exit. Here's a stack overflow thread that goes into a little more detail.

Cheers

_Ben