"" />
SoFunction
Updated on 2025-03-10

Under what circumstances can you not write PHP's closed tag "?>"

In some PHP projects, we often see that some PHP files have only the start tag but no end tag. So under what circumstances can this end tag be written without it, and under what circumstances must it be written?

Let’s first look at two examples:

The following code works normally:

<?php
  echo 123456;

The following code will report an error:

<?php
  echo 123456;
  <p>abc</p>

Cause analysis:
The former is pure PHP code, and you can not write an end tag, and it is not recommended to write an end tag; the latter is not only PHP code, but also HTML code, and you must write an end tag.
 
So why not recommend the former to write an end tag?
Because when you do not write the php end tag, the default is php code from the start tag to the back. If there are other codes, an error will be reported.PHP can only run scripts in the php tag. All characters outside the script, including spaces or carriage return and tab symbols that you cannot see, will respond to the client as output content, which may cause unexpected things.. For example, the header function is used in the file, and this file also contains another file, and there are empty characters outside the php tag of the included file. At this time, the header already send error will be reported. When we look at the source code of some web pages, we see that there are many spaces and line breaks at the beginning, which is because of this reason.

Solution suggestions:

Library files, or some class files, etc.Files with only pure php code are not recommended to add end tags

I believe that the description in this article has certain reference value for everyone's PHP programming.