Why does PHP add "\r\n" to an empty string? - php

I’m trying to implement a simple service in PHP. The service needs to return strings to certain requests. However, when I try to echo the string, PHP somehow adds \r\n to the beginning of the string. I am using echo to output the response.
I tried to echo one space character:
$test = ' ';
echo $test;
and in the response I still got '\r\n'.
I have tried header('Content-type: text'); and $string = preg_replace("\r\n", "", $string);, but I’m still getting the new line in the response.
I’m new to PHP, so if this is some kind of concept, could someone provide me with pointers to information where I can read about it?

It's possible this character is in your sourcecode somewhere, for instance at the end of one your scripts, like: ?>\r\n.
A best practice is to never include the final ?> in each file to avoid accidental output.
This recommendation is in the PSR-2 Coding Style Guide.
The closing ?> tag MUST be omitted from files containing only PHP.
It's also in the manual.
If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.

Related

Netbeans advises me to not have a closing page tag in PHP, why?

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?
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.

justification for removing closing tag from a PHP file [duplicate]

This question already has answers here:
Why would one omit the close tag?
(14 answers)
Closed 8 years ago.
OK, I hate doing something for no reason, especially if it appears to be the stupidest thing I've ever seen, so here goes:
I'm encountering a codebase where the PHP files start with <?php, but don't end with ?>
I have not seen any documentation on why, but apparently this has something to do with "security".
Can someone enlighten me as to why I would break with common sense and leave out the closing PHP tag at the bottom of a file?
The documentation states:
If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.
It has nothing to do with "security". It has something to do with functions whose behaviour depends on whether output has already been sent to the client or not. The best example is the function header(). It is meant for manipulating the HTTP response headers. This function will work only before any output has been send - as in HTTP there headers cannot being sent after the body.
Let's get back to the nature of PHP. It is a scripting language which can be embedded into other documents, like HTML:
<html>
<head><title><?php echo $title; ?></title></head>
<body><?php echo $body; ?></body>
</html>
When embedded into other documents PHP's output will be inserted into the document, leaving the original document as-is, meaning just sending it's literal content to the client.
When you have a class file, for example:
<?php
class Foo {
}
?><whitespace>...
<newline>
<newline>
... you are closing the PHP tag and have two forgotten spaces and new lines in the file. PHP would send those spaces and new lines to the client, meaning a function like header() wouldn't work anymore. This simply a text document with embedded PHP code. (Unlike source code files in other languages). PHP will replace the part between the <?php ?> and send the results + remaining parts of the file to the client.
If you omit the closing PHP tag in this case, the PHP parser would just ignore the spaces and newlines because they don't contain code.
According to php.net reason behind avoiding ending php tag is:
"If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script."

Laravel displays an empty line before the Doctype

<!DOCTYPE html>
This is the code.
How can I fix that?
I tested the HTML/CSS/JavaScript before integrating the code with Laravel.
Make sure your PHP files don't have the closing tags (?>). They might add whitespace to your HTML.
For more info, see the PHP docs:
If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.
You might also want to take a look at this post: Why would one omit the close tag?
I know this is few years late but for other people.
change the page encoding to UTF-8 without BOM and it will be solved.

Debugging PHP Output

I have a php website that on certain pages is adding a dot or space before the first html tag. I can't figure out where it is coming from - is there a way to debug the code so i can see where it is coming from?
Thanks,
Josh
To help prevents this happening it is considered a good practice to don't end your PHP file with a ?>.
You possibly have some file that are this way (notice the extra space after the ?>):
<?php
// Some code //
?>
If you would remove the ?> at the end, the extra space at the end of the file won't be interpreted as something to output.
For files that contain only PHP code,
the closing tag ("?>") is never
permitted. It is not required by PHP,
and omitting it´ prevents the
accidental injection of trailing white
space into the response.
Source: http://framework.zend.com/manual/en/coding-standard.php-file-formatting.html
Maybe it is a BOM character?
Maybe you should check your templates if you are using them... the problem could be there and not in your main code.
and yes is a GOOD PRACTICE in PHP not to close the ending tag.
There really is no good way to go about debugging this. You need to go through every file the page is hitting and figure out where the output is coming from. If you really wanted to be lazy about it you could do some output buffering, but this isn't the right way to do things.
Problems like this can be difficult to track down. If you're in some kind of framework or system that includes a lot of files, you might try a var_dump(get_included_files()) on the line before your error occurs, and that will give you a place to start. If that isn't sufficient, xdebug might get you further. Things to look out for are space before and after the PHP tags, and functions that might send output.

PHP tag closing-- when is needed?

It's recommended that one should not put a PHP closing tag at the end of the file to avoid all sorts of untoward error. But is there any circumstances when PHP tag closing is needed?
A closing tag is needed if you want to switch from the PHP code block to the plain text output.
Here’s an example:
<?php
// PHP code block
?>
<!-- plain text output and not processed by PHP -->
</body>
BTW if you want to know what error you are preventing by skipping the closing tag. Since Zend's explanation doesn't go into detail.
It is not required by PHP, and omitting it prevents the accidental injection of trailing white space into the response.
This means that if you want to use header() to redirect some person to some other location or change the HTTP header in any way... then you can't and will get an error if some file ends like this.
}
?>
//space here
Because then this space will be outputted to the site as content and then you can't modify the headers.
This is my personal "rule":
File with only php code: Never end tag
File with php mixed with something else (I.e. HTML): Always end tag
It's only needed when you want to output non-php code after your php block.
When you are not just using PHP in the script :-)
As a general rule, I always add the closing tag, because it's the only time all day that my question-mark finger gets exercise. That poor question mark gets no love in PHP ;-)
But seriously, adding the closing tag when it's not required can actually lead to really confusing errors. I pulled my hair out all afternoon once because of this. The trouble is usually because there's spaces after the closing tag that you can't easily see, but they get interpreted as part of a response body. This is bad news if you're including this file inside another script that wants to send a custom header later on. You can't send header information after a script has started sending the response body, so these little invisible spaces result in the script failing.

Categories