Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

Fedor Zhorin
PLUS
Fedor Zhorin
Courses Plus 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

1 Answer

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