Reputation: 4323
In pretty much every PHP page I have in netbeans, the end of the file usually ends with a closing PHP tag, ?>
If this tag is ever at the very end of the document, NetBeans shows a hint saying
Unnecessary Closing Delimiter
This doesn't seem to follow the general rule of closing tags throughout the rest of the document, why is it not needed at the end, and why does leaving it out not cause an 'Unexpected end of file' error?
Upvotes: 1
Views: 890
Reputation: 40916
Only exit PHP mode if you want to output something to the browser after the end of the script. Eg:
<?php
do_something_function();
?>
<div> this is HTML </div>
If you don't intend to send anything else to the browser, closing ?>
leaves open the possibility that you send some whitespace anyway, which could have some unintended effects. Eg. If the user wants to download a secret message, your script might be:
<?php
//set headers for content type and size
//send message
echo $encrypted_msg;
?>
(<< there is unintended white-space here)
Because you are sending some white-space after the closing ?>
, what the browser will receive is not what's expected. The message is probably corrupt and decryption will fail.
Another, perhaps more typical example. Suppose your front end code makes an ajax request to the php script and expects to receive JSON encoded info. Here is the script:
<?php
header('Content-type: application/json');
echo json_encode(['name'=>'Dana']);
?>
(<< white-space)
In Firefox, the whitespace at the end will case a 400 Bad Request
error because it turns the server response into badly formed JSON.
A much harder to fix problem can occur if the white-space is not in the file you're actively writing, but in another included file. Consider this situation:
main.php
<?php
include 'value.php';
setcookie('pref_language', 'english'); //to remember user's preference
echo $value;
value.php
<?php
$value = 'Hi, this is value.php';
?>
(<< white-space)
Even though the file you're coding (main.php) is well written, the code will fail because cookies and headers must be set before anything is sent to the browser and unfortunately, value.php
is emitting white-space. This kind of error can be a nightmare to deal with if you have large programs that include many scripts.
From the manual: (credit to @chris85 for finding this so fast)
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.
Upvotes: 2