424

When is it a good idea to use PHP_EOL?

I sometimes see this in code samples of PHP. Does this handle DOS/Mac/Unix endline issues?

Pacerier
  • 86,231
  • 106
  • 366
  • 634
Christian Oudard
  • 48,140
  • 25
  • 66
  • 69
  • 1
    I think there is a lot of misleading advice in the upvoted answers on this page. If you run a script on two different platforms, then compare the output or generated data (log files, html page, database records etc), then the PHP_EOL will result in a mismatch in the diff. In most cases this is not what you want. – donquixote Mar 15 '18 at 14:08
  • 1
    I use `PHP_EOL` when writing scripts to execute and output in a command line terminal - so I know I can force a new line in text output in the terminal. For web applications I'd output `
    ` to force text to a new line (or wrap a block element around the content, like a paragraph or div). So I think answers should clarify the context of the PHP script (terminal application, web application, file creation script etc.) to support the argument for/against the use of `PHP_EOL`.
    – Matt Smith Jul 16 '22 at 09:29
  • @MattSmith If you write a script, then you have to follow the script rules and not the end-of-line of the current system. If writing a bash script, then use `\n`, if you writing a windows script, then use `\r\n`. Both are independent from the current system and from `PHP_EOL`. – Wiimm Sep 07 '22 at 10:58

20 Answers20

412

Yes, PHP_EOL is ostensibly used to find the newline character in a cross-platform-compatible way, so it handles DOS/Unix issues.

Note that PHP_EOL represents the endline character for the current system. For instance, it will not find a Windows endline when executed on a unix-like system.

Adam Bellaire
  • 108,003
  • 19
  • 148
  • 163
  • 14
    Should it be used as the end-line character when writing a command-line script? – Thomas Owens Sep 24 '08 at 17:37
  • 8
    @Andre: How about anyone that writes apps to be installed, used and deployed by others? Are you suggesting these should all limit their "supported platforms" to *nix? – Cylindric Mar 04 '11 at 10:52
  • @Andre Maybe because your deployment platform is Windows Azure? – middus Jul 22 '11 at 17:59
  • 2
    @Stann - What the "big projects" that you know about do is hardly the deciding factor on best practice, let alone what is or is not useful. I maintain a "big project" that is deployed in part on several hosts, including some windows servers. Don't assume -- the constants don't hurt anything, and are a perfectly valid way to write platform-neutral code. Your comments to the contrary are somewhat absurd. – Chris Baker Sep 13 '12 at 19:12
  • This is why in Sublime Text or whatever IDE you use you have the option of using 3 different end of lines, Unix, OSX, DOS, or auto. The correct 'End Of Line' symbol for this platform. Available since PHP 4.3.10 and PHP 5.0.2. http://php.net/manual/en/reserved.constants.php – Michael J. Calkins Nov 17 '13 at 02:43
  • 7
    No, I don't think your answer is correct. You generate code on one system but send the output to another system. PHP_EOL, however, tells you the line ending delimiter ONLY for the system where it is used. It does not guarantee you that the other system uses the same delimiter. See my answer below. – StanE Aug 23 '15 at 11:43
  • "for the local system" should be included, but I think anyone knows that. – Heroselohim May 28 '16 at 19:32
  • 1
    but don't use `PHP_EOL` for data posted from form. – Nabi K.A.Z. Nov 10 '16 at 10:13
  • 1
    There should be an official documentation for `PHP_EOL` on php.net. Searching for `PHP_EOL` does not provide direct landing page ( http://php.net/manual-lookup.php?pattern=php_eol&scope=quickref ). There exists just the info @MichaelJ.Calkins indicated above ( http://php.net/manual/en/reserved.constants.php ). – Peter Dec 20 '17 at 09:35
102

From main/php.h of PHP version 7.1.1 and version 5.6.30:

#ifdef PHP_WIN32
#   include "tsrm_win32.h"
#   include "win95nt.h"
#   ifdef PHP_EXPORTS
#       define PHPAPI __declspec(dllexport)
#   else
#       define PHPAPI __declspec(dllimport)
#   endif
#   define PHP_DIR_SEPARATOR '\\'
#   define PHP_EOL "\r\n"
#else
#   if defined(__GNUC__) && __GNUC__ >= 4
#       define PHPAPI __attribute__ ((visibility("default")))
#   else
#       define PHPAPI
#   endif
#   define THREAD_LS
#   define PHP_DIR_SEPARATOR '/'
#   define PHP_EOL "\n"
#endif

As you can see PHP_EOL can be "\r\n" (on Windows servers) or "\n" (on anything else). On PHP versions prior 5.4.0RC8, there were a third value possible for PHP_EOL: "\r" (on MacOSX servers). It was wrong and has been fixed on 2012-03-01 with bug 61193.

As others already told you, you can use PHP_EOL in any kind of output (where any of these values are valid - like: HTML, XML, logs...) where you want unified newlines. Keep in mind that it's the server that it's determining the value, not the client. Your Windows visitors will get the value from your Unix server which is inconvenient for them sometimes.

I just wanted to show the possibles values of PHP_EOL backed by the PHP sources since it hasn't been shown here yet...

AlexV
  • 22,658
  • 18
  • 85
  • 122
  • 4
    Wow. The PHP developers are just wrong about this. As the Wikipedia link you give mentions, Mac OS 9 and before used "\r", but not OS X, which uses "\n". Someone should file a bug report... – imgx64 Jan 28 '12 at 07:32
  • 33
    @imgx64 Yeah maybe, but honestly did you ever saw a production MAC server? – AlexV Jan 30 '12 at 13:53
  • 5
    @imgx64 It has been fixed 33 days after your post :) I've updated my answer to reflect current sources. – AlexV Jan 25 '13 at 16:33
  • 4
    I don't think that the argument to use PHP_EOL for output (!) is valid. PHP_EOL is server-side while the output is normally for the client (which uses different line ending delimiters). Example: If you create a multi-line plain text output on a linux system with PHP_EOL and send it to a Windows system, it will not be a valid line ending delimiter - it will depend what client software will display the output. Browsers and some text editors might handle it, but if you view the text for example in Notepad, everything will be in one line. – StanE Aug 23 '15 at 10:47
  • 1
    `php -r "echo addcslashes(PHP_EOL, PHP_EOL), PHP_EOL;"` to find out. – Bob Stein Nov 09 '17 at 16:04
87

You use PHP_EOL when you want a new line, and you want to be cross-platform.

This could be when you are writing files to the filesystem (logs, exports, other).

You could use it if you want your generated HTML to be readable. So you might follow your <br /> with a PHP_EOL.

You would use it if you are running php as a script from cron and you needed to output something and have it be formatted for a screen.

You might use it if you are building up an email to send that needed some formatting.

John
  • 1
  • 13
  • 98
  • 177
Zoredache
  • 37,543
  • 7
  • 45
  • 61
  • 31
    You don't need to use platform-independent newlines when generating HTML. – Rob Apr 21 '09 at 22:00
  • 6
    @Rob, If older versions of IE gave me a better page-source viewer then windows notepad I might have agreed with you. – Zoredache Jan 23 '10 at 01:18
  • 19
    @Zoredache - the HTML will be generated with newlines appropriate for the platform that PHP is running on, not necessarily appropriate for the platform that you're accessing pages from. – Dominic Rodger Feb 02 '10 at 08:43
  • 2
    +1 for mentioning email building `$header = "From: $from" . PHP_EOL; $header .= "Reply-To: $from" . PHP_EOL; $header .= "Return-Path: $from" . PHP_EOL;` – Jakob Cosoroaba May 17 '10 at 12:13
  • 57
    **`PHP_EOL` should not be used for separating email headers.** According to [PHP Mail](http://www.php.net/manual/en/function.mail.php) manual, multiple extra headers should be separated with a CRLF (\r\n). – Halil Özgür Nov 27 '10 at 13:55
  • @HalilÖzgür This is true re. the RFC. But [unfortunately not true in PHP](https://code.google.com/p/simplesamlphp/issues/detail?id=493#c5). And I checked, v5.4.11 has the same code. – Déjà vu Mar 15 '13 at 08:54
  • 1
    @ring0 unfortunately :) Whenever I need sending emails in PHP, most of the time I end up using Swift Mailer; for infinitely many details of email format requirements and PHP inconsistencies. – Halil Özgür Mar 15 '13 at 09:35
  • Example $headers = 'From: webmaster@example.com' . "\r\n" . 'Reply-To: webmaster@example.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); – zloctb Sep 23 '13 at 16:29
  • @halil-ozgur is it okay to use PHP_EOF for lines inside a mail body in PHP? – Lexib0y Feb 04 '14 at 11:41
  • 2
    @Lexib0y TLDR; no, use CRLF. You mean PHP_EOL, right? According to the latest [RFC](http://tools.ietf.org/html/rfc5322#section-2.3), no. You should use CRLF there as well. But various email servers and clients might look like tolerating even if you use PHP_EOL (which is CRLF only on Windows and LF on most others), but I still wouldn't rely on them. – Halil Özgür Feb 04 '14 at 13:33
  • Yes I meant PHP_EOL. Thanks for the info. I find it difficult to find the relative information in one place, or at all. I never really went into RFCs. Thanks for your answer. – Lexib0y Feb 04 '14 at 15:14
  • 2
    `You might use it if you where building up an email to send that needed some formatting.` lol what a horrible example, as if the recipient will definitely be using the same OS. – Samuel Katz Feb 19 '14 at 19:27
22

PHP_EOL (string) The correct 'End Of Line' symbol for this platform. Available since PHP 4.3.10 and PHP 5.0.2

You can use this constant when you read or write text files on the server's filesystem.

Line endings do not matter in most cases as most software are capable of handling text files regardless of their origin. You ought to be consistent with your code.

If line endings matter, explicitly specify the line endings instead of using the constant. For example:

  • HTTP headers must be separated by \r\n
  • CSV files should use \r\n as row separator
Salman A
  • 262,204
  • 82
  • 430
  • 521
14

I'd like to throw in an answer that addresses "When not to use it" as it hasn't been covered yet and can imagine it being used blindly and no one noticing the there is a problem till later down the line. Some of this contradicts some of the existing answers somewhat.

If outputting to a webpage in HTML, particularly text in <textarea>, <pre> or <code> you probably always want to use \n and not PHP_EOL.

The reason for this is that while code may work perform well on one sever - which happens to be a Unix-like platform - if deployed on a Windows host (such the Windows Azure platform) then it may alter how pages are displayed in some browsers (specifically Internet Explorer - some versions of which will see both the \n and \r).

I'm not sure if this is still an issue since IE6 or not, so it might be fairly moot but seems worth mentioning if it helps people prompt to think about the context. There might be other cases (such as strict XHTML) where suddently outputting \r's on some platforms could cause problems with the output, and I'm sure there are other edge cases like that.

As noted by someone already, you wouldn't want to use it when returning HTTP headers - as they should always follow the RFC on any platform.

I wouldn't use it for something like delimiters on CSV files (as someone has suggested). The platform the sever is running on shouldn't determine the line endings in generated or consumed files.

Prasad Rajapaksha
  • 6,118
  • 10
  • 36
  • 52
Iain Collins
  • 6,774
  • 3
  • 43
  • 43
12

No, PHP_EOL does not handle endline issues, because the system where you use that constant is not the same system where you send the output to.

I would not recommend using PHP_EOL at all. Unix/Linux use \n, MacOS / OS X changed from \r to \n too and on Windows many applications (especially browsers) can display it correctly too. On Windows, it is also easy change existing client-side code to use \n only and still maintain backward-compatibility: Just change the delimiter for line trimming from \r\n to \n and wrap it in a trim() like function.

StanE
  • 2,704
  • 29
  • 38
  • 4
    Would be nice to know why my answer is downvoted... Crazy... The accepted answer is *wrong*, while mine is correct. It is not generally correct to say that PHP_EOL handles the issue. It can (and should) be used if reading or writing SOLELY something to / from the *same* system. But most of the time PHP is used to send something back to the client (which is most likely what the questioneer thought about). Again: PHP_EOL is a pure server-side constant. It does NOT (and can't) handle client side line breaks correctly. Please write a comment and tell me, if you think that I wrote something wrong. – StanE Jul 10 '16 at 17:04
  • 4
    +1 for making a good point against the grain. I think it's lost because browsers don't render whitespace in html, so the common use would be for console applications. And as you said, in that case the line ending would be interpreted for the executing environment, which makes sense for console apps, but not client-server web applications. – Jeff Puckett Sep 22 '16 at 12:02
  • Well, the answer doesn't really relate. You mention browser compatibility and sending files to other systems. Newline is relevant in text output, so browsers aren't relevant. And contrary to your main point, these text files *are* usually consumed on the same platform they're written on. – grantwparks Oct 31 '18 at 05:03
10

I found PHP_EOL very useful for file handling, specially if you are writing multiple lines of content into a file.

For example, you have a long string that you want to break into the multiple lines while writing into plain file. Using \r\n might not work so simply put PHP_EOL into your script and the result is awesome.

Check out this simple example below:

<?php

$output = 'This is line 1' . PHP_EOL .
          'This is line 2' . PHP_EOL .
          'This is line 3';

$file = "filename.txt";

if (is_writable($file)) {
    // In our example we're opening $file in append mode.
    // The file pointer is at the bottom of the file hence
    // that's where $output will go when we fwrite() it.
    if (!$handle = fopen($file, 'a')) {
         echo "Cannot open file ($file)";
         exit;
    }
    // Write $output to our opened file.
    if (fwrite($handle, $output) === FALSE) {
        echo "Cannot write to file ($file)";
        exit;
    }
    echo "Success, content ($output) wrote to file ($file)";
    fclose($handle);
} else {
    echo "The file $file is not writable";
}
?>
Tyzoid
  • 1,072
  • 13
  • 31
ip bastola
  • 101
  • 1
  • 3
6

The definition of PHP_EOL is that it gives you the newline character of the operating system you're working on.

In practice, you should almost never need this. Consider a few cases:

  • When you are outputting to the web, there really isn't any convention except that you should be consistent. Since most servers are Unixy, you'll want to use a "\n" anyway.

  • If you're outputting to a file, PHP_EOL might seem like a good idea. However, you can get a similar effect by having a literal newline inside your file, and this will help you out if you're trying to run some CRLF formatted files on Unix without clobbering existing newlines (as a guy with a dual-boot system, I can say that I prefer the latter behavior)

PHP_EOL is so ridiculously long that it's really not worth using it.

Edward Z. Yang
  • 26,325
  • 16
  • 80
  • 110
4

There is one obvious place where it might be useful: when you are writing code that predominantly uses single quote strings. Its arguable as to whether:

echo 'A $variable_literal that I have'.PHP_EOL.'looks better than'.PHP_EOL;  
echo 'this other $one'."\n";

The art of it is to be consistent. The problem with mix and matching '' and "" is that when you get long strings, you don't really want to have to go hunting for what type of quote you used.

As with all things in life, it depends on the context.

SjH
  • 99
  • 1
  • 1
3

I use the PHP_EOL constant in some command line scripts I had to write. I develop on my local Windows machine and then test on a Linux server box. Using the constant meant I didn't have to worry about using the correct line ending for each of the different platforms.

chrismacp
  • 3,834
  • 1
  • 30
  • 37
3

DOS/Windows standard "newline" is CRLF (= \r\n) and not LFCR (\n\r). If we put the latter, it's likely to produce some unexpected (well, in fact, kind of expected! :D) behaviors.

Nowadays almost all (well written) programs accept the UNIX standard LF (\n) for newline code, even mail sender daemons (RFC sets CRLF as newline for headers and message body).

mvp
  • 111,019
  • 13
  • 122
  • 148
Nica Mlg
  • 31
  • 1
2

Handy with error_log() if you're outputting multiple lines.

I've found a lot of debug statements look weird on my windows install since the developers have assumed unix endings when breaking up strings.

Gavin Gilmour
  • 6,833
  • 4
  • 40
  • 44
2

I have a site where a logging-script writes a new line of text to a textfile after an action from the user, who can be using any OS.

Using PHP_EOL don't seem to be optimal in this case. If the user is on Mac OS and writes to the textfile it will put \n. When opening the textfile on a windows computer it doesn't show a line break. For this reason i use "\r\n" instead which works when opening the file on any OS.

intTiger
  • 31
  • 3
2

I just experienced this issue when outputting to a Windows client. Sure, PHP_EOL is for server side, but most content output from php is for windows clients. So I have to place my findings here for the next person.

A) echo 'My Text' . PHP_EOL; // Bad because this just outputs \n and most versions of windows notepad display this on a single line, and most windows accounting software can't import this type of end of line character.

B) echo 'My Text \r\n'; //Bad because single quoted php strings do not interpret \r\n

C) echo "My Text \r\n"; // Yay it works! Looks correct in notepad, and works when importing the file to other windows software such as windows accounting and windows manufacturing software.

hamish
  • 1,141
  • 1
  • 12
  • 21
1

You are writing code that predominantly uses single quote strings.

echo 'A $variable_literal that I have'.PHP_EOL.'looks better than'.PHP_EOL;  
echo 'this other $one'."\n";
1

I am using WebCalendar and found that Mac iCal barfs on importing a generated ics file because the end-of-line is hardcoded in xcal.php as "\r\n". I went in and replaced all occurrences with PHP_EOL and now iCal is happy! I also tested it on Vista and Outlook was able to import the file as well, even though the end of line character is "\n".

Lex
  • 11
  • 2
  • That means your application will malfunction when it's deployed on a Windows server. If you want `\n`, use that explicitly. –  Nov 16 '17 at 01:53
0

When jumi (joomla plugin for PHP) compiles your code for some reason it removes all backslashes from your code. Such that something like $csv_output .= "\n"; becomes $csv_output .= "n";

Very annoying bug!

Use PHP_EOL instead to get the result you were after.

sjngm
  • 12,423
  • 14
  • 84
  • 114
Allan
  • 1
  • 2
    i would really REALLY hope this is a configuration issue you haven't found yet. i havent used joomla, but what an awful behavior if thats really how it works! – jon_darkstar Dec 06 '10 at 21:52
0

On some system may be useful to use this constant because if, for example, you are sending an email, you can use PHP_EOL to have a cross-system script working on more systems... but even if it's useful sometime you can find this constant undefined, modern hosting with latest php engine do not have this problem but I think that a good thing is write a bit code that saves this situation:

<?php
  if (!defined('PHP_EOL')) {
    if (strtoupper(substr(PHP_OS,0,3) == 'WIN')) {
      define('PHP_EOL',"\r\n");
    } elseif (strtoupper(substr(PHP_OS,0,3) == 'MAC')) {
      define('PHP_EOL',"\r");
    } elseif (strtoupper(substr(PHP_OS,0,3) == 'DAR')) {
      define('PHP_EOL',"\n");
    } else {
      define('PHP_EOL',"\n");
    }
  }
?>

So you can use PHP_EOL without problems... obvious that PHP_EOL should be used on script that should work on more systems at once otherwise you can use \n or \r or \r\n...

Note: PHP_EOL can be

1) on Unix    LN    == \n
2) on Mac     CR    == \r
3) on Windows CR+LN == \r\n

Hope this answer help.

Alessandro
  • 900
  • 12
  • 23
-1

I use the PHP_EOL constant when I don't have a browser handy with my PHP. Well actually, I use it indirectly. View the example below.
For example, there's this site called code.golf (which is basically stack exchange code golf but interactive). There's a PHP one where there's only console output, and I need to use the PHP_EOL constant to use this.

A way to shorten it is that once you need to use the PHP_EOL constant, just do something like this:

<?php
echo $n = PHP_EOL;
?>

That declares the variable $n, which you can use instead of the PHP_EOL constant as a newline. Even shorter than <br>, and you can use $n for almost anything that needs a newline!

DaCuteRaccoon
  • 224
  • 2
  • 13
-2

I prefer to use \n\r. Also I am on a windows system and \n works just fine in my experience.

Since PHP_EOL does not work with regular expressions, and these are the most useful way of dealing with text, then I really never used it or needed to.