开发者

Omitting Closing Php Tag [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Why do some scripts omit the closing php tag '?>'?

I've been reading some articles about Omitting Closing PHP tags since they say it is a good programming practice in PHP if your .php file doens't contain any other 开发者_运维技巧things. There are many questions like that but after I tried what they've done so far worked well on my machine. Maybe it is a fixed issue or something?

But I don't quite understand why it could be a good programming practice since it brings space or something but I've tried this one and works very well.

Master.php

<?php

echo "Master.php";

include "Slave.php";

header("Location:Slave.php");

?>

Slave.php

<?php

echo "Slave.php";

?> 

I don't really quite get what the problem should be if I didn't use closing php tag.

Thanks.


The main issue is you may include additional whitespace (but it can be any chars) after the closing ?> (besides one \n which PHP allows, thanks Mario).

This extra whitespace appears to PHP as output to be sent. This makes PHP start sending the response body, therefore making any additional headers being set/modified impossible.

This is hard to debug (as whitespace is generally invisible in text editors) and often the cause of the dreaded Headers already sent error.


the problem with the closing tag is that any whitespace after the last ?> may cause bugs and is very difficult to detect while bug fixing.


It is usually better to NOT end your script with closing PHP tag.

In your case a whitespace could remain after ?> (it is very sneaky and hard to tell where error is if something breaks because of this reason), so it would be considered as output and you won't be able to start session, for example or pass headers in case if you are developing a website.

Just my opinion. I likely never end my scripts with closing tag


The problem comes from having any number of line breaks other than 1: some php parsers get upset if there isn't a newline at that end, but if you have more than one, it is printed since anything outside php tags is considered HTML.

The most common problem is that a library/model file will have an extra line break, causing the headers to be sent long before the page/view is instantiated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜