Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Omitting Closing Php Tag [duplicate]

Tags:

php

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.

like image 579
Tarik Avatar asked Jun 01 '11 04:06

Tarik


People also ask

Is it OK to not close the PHP tag?

If a file contains only PHP code, it is preferable to omit the PHP closing tag at the end of the file.

Why is it considered a best practice to avoid using a PHP closing tag ?> In PHP files that contain only PHP code?

It is recommended that a closing PHP tag shall be omitted in a file containing only PHP code so that occurrences of accidental whitespace or new lines being added after the PHP closing tag, which may start output buffering causing uncalled for effects can be avoided.

How do I end a PHP tag?

As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block.


2 Answers

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.

like image 177
alex Avatar answered Sep 24 '22 07:09

alex


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.

like image 25
David Chan Avatar answered Sep 20 '22 07:09

David Chan