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 trialLuca Vicini
Courses Plus Student 8,594 Pointsexit(); after header("Location: shirts.php"); is it really necessary?
I am wondering why we need to place an exit(); command after the header instruction. If execution is passed to shirts.php why do we need the exit(); anyway?
3 Answers
David Omar
5,676 Pointsexit() terminates the current script. My basic understanding of it is that the header function doesn't immediately terminate the connection and the code after can still be executed. So adding exit after header is to make sure that code after it won't be executed. I'm sure this isn't the best answer but it's enough of an answer for me.
Luca Vicini
Courses Plus Student 8,594 PointsThanks for your answers!! It's quite interesting. In languages like Java, C or Pascal, exit() or a similar goto() style command is most of the time considered sloppy programming, while in PHP it looks like it's considered normal practice (even a necessity).
I distress here, but I'm still getting used to the weakly typed nature of PHP. Writing something like: $x = 10 + "3"; in PHP gives $x =13; fantastic freedom but prone to extremely sloppy code unless you know exactly how types are going to be converted.
Getting used to all this...
Shawn Gregory
Courses Plus Student 40,672 PointsHello,
You can also combine the two lines into one since exit() can take a parameter that is performed before the script exits.
exit(header("Location: index.php"));
Of course in my scripts I use the die() function (which isn't that different from exit()).
Cheers!
thomascawthorn
22,986 Pointsthomascawthorn
22,986 PointsYeah, that's it! header() will not stop the script and things below will continue to be parsed. If you scroll down to the comments on the php function page for exit(), some people have added hints and tips to make this action a little cleaner... if you feel up for a challenge!