Looking into code of few sites I noted that some php files have ?>
at the end of file and some doesn't. Doesn't it matter - and if it does, when must I put ?>
at the end of the file and when mustn't I?

- 12,105
- 14
- 57
- 95
-
It will make the compiler to understand the php coding has ended with ?> – NMN Apr 20 '15 at 10:01
-
3Good practice not to close PHP tag. – Sumit Apr 20 '15 at 10:01
-
1Only when you want to explicitly exit PHP do you need one, if you don't have one and PHP hits the end of your page, it will terminate automatically. – naththedeveloper Apr 20 '15 at 10:01
-
2good read here: http://stackoverflow.com/questions/4410704/why-would-one-omit-the-close-tag – n-dru Apr 20 '15 at 10:01
-
1@Sumit I would argue the opposite. It's always a good practice to close your opening tags. – Tomasz Cz. Apr 20 '15 at 10:02
-
@TomaszCz. - I see too many cases of newlines or white space after a closing `?>` corrupting output.... common practise these days is to avoid using `?>` to prevent exactly that problem – Mark Baker Apr 20 '15 at 10:05
-
@TomaszCz this is the issue and good to avoid headers already sent issues. – Sumit Apr 20 '15 at 10:10
-
Thanks for clarification guys. I understand your point. Never thought of this that way. – Tomasz Cz. Apr 20 '15 at 10:13
3 Answers
Never use ?>
at the end of the file.
It's entirely optional but including it provides the opportunity to slip whitespace into the output by accident. If you do that in a file that you include
or require
before you try to output headers then you'll break your code.
Putting ?>
at the end of a PHP file has only drawbacks.

- 914,110
- 126
- 1,211
- 1,335
Putting ?>
is optional if it is the last PHP tag. Omitting it in the last tag will benefit you in one case. There may be case where text editor append hidden special character after that tag. This could create problem. Omitting last closing tag will solve this problem.

- 1,732
- 6
- 18
- 23
From PHP Official Documentation - Instruction separation
The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include or require, so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.

- 94,083
- 31
- 258
- 268