\r\n 和 \n 之间的 PHP 区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2115549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:05:44  来源:igfitidea点击:

PHP difference between \r\n and \n

phpsyntax

提问by johnnietheblack

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:

我见过有人告诉我在不同的地方使用“\r\n”,而其他人告诉我在同一个地方使用“\n”。我确定一个是对的,一个是错的。示例 - 设计 mail() 标头时:

Tutorial #1:

教程#1:

//define the headers we want passed. Note that they are separated with \r\n 
$headers = "From: [email protected]\r\nReply-To: [email protected]"; 
//add boundary string and mime type specification 
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\""; 

Tutorial #2 (notice the header argument):

教程#2(注意标题参数):

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

我很困惑,但显然这有点不同,因为对于一个,我的标题有效,而对于另一个,它们只是有时有效。

回答by Yada

\r\n are end of line characters for Windows systems.

\r\n 是 Windows 系统的行尾字符。

\n is the end of line character for UNIX systems.

\n 是 UNIX 系统的行尾字符。

These characters are invisible. From my own experience \n is usually okay for Windows as well.

这些字符是不可见的。根据我自己的经验, \n 通常也适用于 Windows。

Some prefer to use PHP_EOLconstant instead of these characters for portability between platforms.

有些人更喜欢使用PHP_EOL常量而不是这些字符来实现平台之间的可移植性。

echo 'hi' . PHP_EOL;
echo "hi\n";

$headers = "From: [email protected]" . PHP_EOL 
           . "Reply-To: [email protected]"; 

回答by Max Shawabkeh

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\nbut not \n).

根据RFC 821(SMTP 协议),邮件标题和内容中的行尾应该始终是\r\n( <CR><LF>),但实际上这无关紧要,因为大多数邮件服务器都正确处理所有三种类型的行尾(据说,一些旧的 UNIX-基于的实际上窒息\r\n但不是\n)。

回答by Dominik Sandjaja

In addition to Yada's answer, here is an explaining blog entry: https://blog.codinghorror.com/the-great-newline-schism/

除了雅达的回答,这里有一个解释性的博客条目:https: //blog.codinghorror.com/the-great-newline-schism/

[Update 2017-05-24: Fixed the link]

[2017-05-24 更新:修复链接]