PHP difference between \r\n and \n
Simple question...
开发者_开发知识库I have seen people tell me to use "\r\n" in various places and others tell me to use "\n" in the same place. I'm sure one is right and one is wrong. Example - when designing mail() headers:
Tutorial #1:
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
Tutorial #2 (notice the header argument):
mail($to, $subject, $body,
"From: " . $from . "\n" .
"bcc: " . $bcc . "\n" .
"MIME-Version: 1.0\n" .
"Content-Type: multipart/alternative;\n" .
" boundary=" . $mime_boundary_header)
I am confused, but clearly it makes somewhat of a difference, because with one, my headers worked, and with the other they only sometimes work.
\r\n are end of line characters for Windows systems.
\n is the end of line character for UNIX systems.
These characters are invisible. From my own experience \n is usually okay for Windows as well.
Some prefer to use PHP_EOL constant instead of these characters for portability between platforms.
echo 'hi' . PHP_EOL;
echo "hi\n";
$headers = "From: webmaster@example.com" . PHP_EOL
. "Reply-To: webmaster@example.com";
As per RFC 821 (the SMTP protocol), line endings should always be \r\n
(<CR><LF>
) in mail headers and content, but in practice it shouldn't matter as most mail servers handle all three type of line endings correctly (supposedly, some old UNIX-based ones actually choke on \r\n
but not \n
).
In addition to Yada's answer, here is an explaining blog entry: https://blog.codinghorror.com/the-great-newline-schism/
[Update 2017-05-24: Fixed the link]
精彩评论