deir9g
Last Updated: February 25, 2016
·
1.341K
· mauris

Write PHP scripts without ?>

It is good practice that all PHP files should have only one opening <?php and the rest of the file is defined to be only PHP. If you need to render HTML, put that into another file and use your PHP script to render that HTML file instead.

This reduces problems such as ghost whitespaces causing "Output already written before header" errors.

3 Responses
Add your response

3461

I knew it was a good practice but I didn't know why. Thanks for sharing.

over 1 year ago ·
3921

It also keeps your functionality clean from the presentation... Much like how one should NEVER write inline CSS, always keep your styling out of your HTML. For the love of god.

I opened an ASP file today that had all the HTML in the top, then all the jquery in the last 1000 lines. Inline CSS ever'where... I had to open it because the developer couldnt figure out why she was getting errors... blink

over 1 year ago ·
3985

It is already in a lot of PHP coding guidelines to not close the PHP-tag at the end of the file. In theory it is unclean as in some cases PHP might complain about it. But on the other hand it is avoiding a lot of problems. And that might be the reason a lot of PHP developers use this.

I guess one of the most common problems is when you start searching for a "header already sent by ..." error. It most of the time is caused by a file that has a closing PHP-tag followed by some kind of white-space usually. Finding those file(s) in a project with a couple of files can already be some work. But if all files don't have the closing PHP-tag, this can never happen.

So in summary, it is in terms of PHP unclean but helps soooo much avoiding mistakes that it is still a good idea to not close PHP tags.

The tip to just open the PHP tag ONCE in file is a great advice. You still have a couple of options to output html to the browser ... via echo or similar, separate file that contains only html, ...

And of course some learned it ... Separate logic from the view/UI. That is always a good idea!

over 1 year ago ·