8

I see a lot of PHP email implementations using "\r\n", but I have also seen some of them using the PHP_EOL constant. Which one is better?

Thanks for any help
Metropolis

Metropolis
  • 6,542
  • 19
  • 56
  • 86

3 Answers3

18

If this is to terminate lines in an email then it's the spec for email that you need to look at, not what is used on any particular platform.

Lines in email are terminated by CRLF ("\r\n") according to RFC2821

SMTP commands and, unless altered by a service extension, message data, are transmitted in "lines". Lines consist of zero or more data characters terminated by the sequence ASCII character "CR" (hex value 0D) followed immediately by ASCII character "LF" (hex value 0A). This termination sequence is denoted as in this document. Conforming implementations MUST NOT recognize or generate any other character or character sequence as a line terminator

That seems pretty clear that in an email the end of line is to be sent as \r\n . Sending anything else might work but it's wrong unless you are using a "service extension" and if you are then you probably know what you should be sending anyway.

jcoder
  • 29,554
  • 19
  • 87
  • 130
  • +1 for consulting the RFC. Now that you've posted that, I have a vague recollection of reading that once. – George Marian Jul 14 '10 at 16:26
  • 1
    PHP on Linux seems to use \n to separate header lines when the mail() command is used. So if you use \r\n within a custom header, some mail servers interpret this as two newline chars and show part of the header in the mail. (sorry for the year-late comment, but this is still a problem in PHP 5.2, see also http://fluxbb.org/development/core/tickets/667/) – BurninLeo Nov 29 '12 at 18:44
  • @BurninLeo Would you by chance know if the problem is fixed in later versions? – Déjà vu Mar 15 '13 at 06:19
  • I do not know. Actually I do not even know if this misbehavior is caused by PHP or by Postfix. It is probably postfix that *expects* LF instead of CR+LF on a Linux machine (see https://bugs.php.net/bug.php?id=15841) – BurninLeo Mar 20 '13 at 19:55
1

Just to make sure:

PHP_EOL will have no effect on the email at the receiver side. It will use the new line character combination that is common on the system your PHP script is running on.

So if you have a Linux/Unix server, PHP_EOL will result in \n and if you have a Windows server, it will be \r\n.

Today, it should not matter that much which you use and I think that most Windows email applications can also handle just \n (afaik even WordPad understands this, it is Notepad that has problems).

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

\r\n is the Windows newline, if you're customers are mostly Windows users then this will do you fine.

I also beleive that most non-Windows email clients will compensate for this anyway, so \r\n should not be an issue on Mac or *Nix.

thomasfedb
  • 5,990
  • 2
  • 37
  • 65