When do I use the PHP constant "PHP_EOL"?
Asked Answered
A

19

432

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?

Applicative answered 24/9, 2008 at 17:34 Comment(3)
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.Futurity
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 <br> 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.Implement
@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.Phene
W
421

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.

Wiltshire answered 24/9, 2008 at 17:35 Comment(9)
Should it be used as the end-line character when writing a command-line script?Esquivel
@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?Asti
@Andre Maybe because your deployment platform is Windows Azure?Connective
@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.Truelove
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. php.net/manual/en/reserved.constants.phpZoosporangium
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.Mocambique
"for the local system" should be included, but I think anyone knows that.Artemas
but don't use PHP_EOL for data posted from form.Dampier
There should be an official documentation for PHP_EOL on php.net. Searching for PHP_EOL does not provide direct landing page ( php.net/manual-lookup.php?pattern=php_eol&scope=quickref ). There exists just the info @MichaelJ.Calkins indicated above ( php.net/manual/en/reserved.constants.php ).Emilemile
P
103

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

Pressman answered 12/7, 2011 at 15:15 Comment(6)
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...Rouen
@Rouen Yeah maybe, but honestly did you ever saw a production MAC server?Pressman
@Rouen It has been fixed 33 days after your post :) I've updated my answer to reflect current sources.Pressman
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.Mocambique
php -r "echo addcslashes(PHP_EOL, PHP_EOL), PHP_EOL;" to find out.Giulio
use PHP_EOL when generating PHP code like in a class or code generator. Certainly when under some sort of source control like git. otherwise unnecessary code changes will confuse itRadioelement
E
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.

Endocardial answered 24/9, 2008 at 19:35 Comment(12)
You don't need to use platform-independent newlines when generating HTML.Jacklynjackman
@Rob, If older versions of IE gave me a better page-source viewer then windows notepad I might have agreed with you.Endocardial
@Endocardial - 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.Principe
+1 for mentioning email building $header = "From: $from" . PHP_EOL; $header .= "Reply-To: $from" . PHP_EOL; $header .= "Return-Path: $from" . PHP_EOL;Downdraft
PHP_EOL should not be used for separating email headers. According to PHP Mail manual, multiple extra headers should be separated with a CRLF (\r\n).Uneasy
@HalilÖzgür This is true re. the RFC. But unfortunately not true in PHP. And I checked, v5.4.11 has the same code.Firstnighter
@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.Uneasy
Example $headers = 'From: [email protected]' . "\r\n" . 'Reply-To: [email protected]' . "\r\n" . 'X-Mailer: PHP/' . phpversion();Modern
@halil-ozgur is it okay to use PHP_EOF for lines inside a mail body in PHP?Hussite
@Hussite TLDR; no, use CRLF. You mean PHP_EOL, right? According to the latest RFC, 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.Uneasy
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.Hussite
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.Serval
E
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
Erlandson answered 7/1, 2013 at 13:6 Comment(2)
source for "HTTP headers must be...": ietf.org/rfc/rfc2616.txt chapter 4 section 1Clothbound
SMTP message lines must be terminated by \r\nGiulio
D
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.

Deflocculate answered 15/5, 2013 at 11:20 Comment(0)
M
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.

Mocambique answered 23/8, 2015 at 11:35 Comment(3)
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.Mocambique
+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.Oscar
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.Oversweet
H
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";
}
?>
Houseline answered 4/10, 2010 at 7:59 Comment(1)
\n\r will never work as the sequence is meant to be \r\n </pedantry>Fortran
I
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.

Inedible answered 21/4, 2009 at 22:6 Comment(4)
-1 for "PHP_EOL is so ridiculously long". It's not a valid argument.Medlock
I completely agree with you. There is no sense whatsoever in deploying php on anything but *nix. Thus - there is no point in using PHP_EOL or DIRECTORY_SEPARATOR.Achievement
@Achievement Can you explain your point about "There is no sense whatsoever in deploying php on anything but *nix" ?Hydrochloride
@Hydrochloride I believe that would be called "sarcasm".Papaveraceous
N
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.

Nickelous answered 9/2, 2011 at 11:3 Comment(0)
D
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.

Dani answered 8/9, 2009 at 15:1 Comment(0)
T
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).

Tracee answered 14/1, 2011 at 17:15 Comment(0)
E
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.

Emrick answered 22/6, 2009 at 12:25 Comment(0)
V
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.

Villain answered 18/7, 2014 at 8:16 Comment(0)
E
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.

Evoke answered 5/11, 2019 at 4:44 Comment(0)
D
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".

Debroahdebs answered 6/11, 2009 at 18:24 Comment(1)
<late> That means your application will malfunction when it's deployed on a Windows server. If you want \n, use that explicitly.Politburo
G
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";
Gastrology answered 13/3, 2013 at 11:54 Comment(0)
P
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.

Postilion answered 18/5, 2010 at 2:20 Comment(1)
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!Mangrum
I
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.

Island answered 10/3, 2019 at 9:16 Comment(0)
E
-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.

Eastbourne answered 11/12, 2009 at 1:17 Comment(2)
Beware with the newline char order, it should be \r\n (CR+LF): en.wikipedia.org/wiki/NewlineLazuli
You do not use it but your site can be open by any one on any pc so it may be a issueHorning

© 2022 - 2024 — McMap. All rights reserved.