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

3.6k views Asked by At

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?

1

There are 1 answers

9
Halcyon On BEST ANSWER

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.