Question
When is it appropriate to use the PHP constant PHP_EOL? I see it in PHP code samples. Does it handle line-ending differences between Windows (DOS), macOS, and Unix-like systems?
Short Answer
PHP_EOL represents the newline sequence used by the operating system running PHP. It is most useful for command-line output and text files intended for that local system. You will also learn when an explicit newline such as "\n" or "\r\n" is the correct choice instead.
Concept
PHP_EOL is a built-in PHP constant whose value is the platform's native end-of-line sequence.
var_dump(PHP_EOL);
Typical values are:
- Unix-like systems, including Linux and modern macOS:
"\n"(line feed, LF) - Windows:
"\r\n"(carriage return + line feed, CRLF)
Use it when PHP is producing plain text for the machine on which the code is running, such as a CLI report, a local log-like text export, or a text file intended to follow that operating system's convention.
It does handle the common Windows versus Unix line-ending difference automatically because PHP selects the value based on the system where PHP runs. However, PHP_EOL is not a universal replacement for every newline. Some formats and network protocols require one exact sequence regardless of the server's operating system.
Mental Model
Think of PHP_EOL as a local translator for the instruction “start a new line.”
Your PHP program says, “I need a line break,” and PHP_EOL supplies the line-break style that is customary in its current environment:
- A PHP program running on Linux receives
"\n". - The same program running on Windows receives
"\r\n".
This is useful when the output belongs to the local machine. But if you are filling in an official form with a strict format—such as an HTTP message or CSV specification—you must use the exact format the form requires, not the local translator's preference.
Syntax and Examples
Append PHP_EOL to a string wherever a native line break is needed.
<?php
echo 'First line' . PHP_EOL;
echo 'Second line' . PHP_EOL;
The . operator concatenates strings. Each PHP_EOL adds the newline sequence for the operating system currently running PHP.
Writing a simple text file:
<?php
$lines = [
'Daily report',
'Status: complete',
'Records processed: 42',
];
file_put_contents('report.txt', implode(PHP_EOL, $lines) . PHP_EOL);
implode(PHP_EOL, $lines) joins the array items with a native newline between them. The final PHP_EOL adds a newline after the last line, which is conventional for many text files.
For a required Unix newline, write "\n" explicitly:
$payload = "first line\nsecond line\n";
For a required CRLF newline, write "\r\n" explicitly:
$httpHeaders = "Content-Type: text/plain\r\n\r\n";
Step by Step Execution
Consider this command-line script:
<?php
$name = 'Mina';
$message = 'Hello, ' . $name . '!' . PHP_EOL;
$message .= 'Your export is ready.' . PHP_EOL;
echo $message;
Execution proceeds as follows:
$nameis assigned the stringMina.- PHP builds the first message line:
Hello, Mina!followed byPHP_EOL. - On Linux or macOS, that ending is
"\n". On Windows, it is"\r\n". .=appends the second line and another platform-native ending to$message.echoprints the completed two-line message.
The visible CLI output is:
Hello, Mina!
Your export is ready.
The invisible bytes at the end of each displayed line vary by operating system.
Real World Use Cases
Common uses of PHP_EOL include:
- CLI tools: Print readable progress, warnings, and reports in terminal scripts.
- Local text exports: Create
.txtreports that open naturally in the operating system where they were generated. - Development scripts: Produce fixture files or simple diagnostic output from maintenance scripts.
- Human-readable application logs: Add a native ending when your application directly writes a simple text log file.
Example: a CLI import summary.
<?php
$processed = 125;
$failed = 3;
echo "Import complete" . PHP_EOL;
echo "Processed: {$processed}" . PHP_EOL;
echo "Failed: {$failed}" . PHP_EOL;
For data interchange, verify the receiving format's rules first. For example, a protocol may require CRLF even if the PHP server runs Linux.
Real Codebase Usage
In production code, developers usually choose a line ending based on the output contract:
- Use
PHP_EOLfor a local CLI message or native text-file output. - Use
"\n"when a project standard, a file format, or a Unix-oriented tool requires LF. - Use
"\r\n"when a protocol explicitly requires CRLF. - Let a library handle formatting when one exists, rather than manually concatenating structured output.
A practical CLI helper can make intent clear:
<?php
function writeLine(string $message): void
{
echo $message . PHP_EOL;
}
writeLine('Starting backup');
writeLine('Backup finished');
For CSV, use fputcsv() to escape fields correctly. If you need a specific line ending, confirm your PHP version and library behavior or write records according to the consumer's documented requirements. Do not assume PHP_EOL is always suitable just because the output is a file.
For web responses, line endings can still help make HTML source or plain text readable, but they do not create visible line breaks in normal HTML rendering. Use HTML elements such as <br> or semantic block elements when displaying separate lines in a browser.
Common Mistakes
Expecting PHP_EOL to create a visible HTML line break
This response contains newlines in the HTML source, but browsers generally collapse whitespace when rendering normal HTML:
<?php
echo 'First line' . PHP_EOL . 'Second line';
Use HTML markup for visual layout instead:
<?php
echo 'First line<br>Second line';
For user-provided text, escape it before output and use an appropriate presentation approach; do not blindly concatenate HTML.
Using PHP_EOL for a protocol with fixed rules
HTTP header lines use CRLF by specification. This is not portable if you use PHP_EOL, because it becomes LF on Linux and macOS:
// Do not use PHP_EOL when manually constructing protocol headers.
$headers = 'X-Mode: test' . PHP_EOL;
When manual construction is genuinely needed, use the required ending:
$headers = "X-Mode: test\r\n";
In most PHP web applications, use PHP's header APIs rather than manually building raw HTTP headers.
Confusing single and double quotes
In PHP, escape sequences are interpreted in double-quoted strings but not ordinary single-quoted strings:
$wrong = 'one\ntwo'; // Contains a backslash and the letter n.
$right = "one\ntwo"; // Contains a newline character.
PHP_EOL works in either kind of quoted context because it is a constant concatenated into the string:
$text = 'one' . PHP_EOL . 'two';
Assuming PHP_EOL describes the file you are reading
PHP_EOL describes the platform running PHP, not necessarily the line ending inside an input file. A Linux server can read a Windows CRLF file, and an input may contain mixed endings. Normalize input deliberately when needed:
$normalized = str_replace(["\r\n", "\r"], "\n", $contents);
Comparisons
| Choice | Meaning | Best use |
|---|---|---|
PHP_EOL | Native line ending of the PHP runtime's operating system | CLI output and local native text files |
"\n" | LF, one line-feed character | Unix-style files, many data formats, and project-standard output |
"\r\n" | CRLF, carriage return followed by line feed | Protocols or formats that explicitly require CRLF |
<br> | HTML line-break element | Visible line break in a browser-rendered HTML page |
fputcsv() | Writes and escapes a CSV row | CSV generation; preferable to manual comma joining |
PHP_EOL is about platform-native text conventions. It is not an HTML formatting feature and is not a substitute for a format specification.
Cheat Sheet
// Print one native line in a CLI script
echo 'Done' . PHP_EOL;
// Join text-file lines using the runtime platform's ending
$contents = implode(PHP_EOL, $lines) . PHP_EOL;
// Require LF regardless of the operating system
$contents = implode("\n", $lines) . "\n";
// Require CRLF regardless of the operating system
$contents = implode("\r\n", $lines) . "\r\n";
PHP_EOLis a built-in constant.- Linux and modern macOS normally use LF (
"\n"). - Windows uses CRLF (
"\r\n"). - Choose
PHP_EOLfor local CLI and native plain-text output. - Follow a protocol or file format's documented line-ending requirement over the local platform.
- Newlines do not normally display as visual line breaks in HTML; use HTML markup for that.
FAQ
What does PHP_EOL mean in PHP?
It means “end of line.” It is a PHP constant containing the newline sequence used by the operating system where PHP is executing.
Is PHP_EOL the same as \n?
Not always. On Linux and modern macOS, it is normally "\n". On Windows, PHP_EOL is normally "\r\n".
Should I use PHP_EOL in a web page?
Usually not for visual formatting. A browser does not normally render a source-code newline as a visible new line in HTML. Use appropriate HTML elements or CSS instead.
Does PHP_EOL make files cross-platform?
It makes generated text follow the platform where PHP runs. That is useful for local files, but it does not guarantee compatibility with a consumer that requires a specific ending. Follow that consumer's specification.
Should I use PHP_EOL in HTTP headers?
No. HTTP has fixed CRLF rules. Prefer PHP's built-in HTTP response functions, such as header(), rather than manually composing headers.
Can PHP read Windows and Unix line endings?
Yes, PHP can read files containing either. However, if you need consistent processing, normalize the input line endings explicitly.
Does macOS use a different PHP_EOL value?
Modern macOS uses LF like other Unix-like systems. Classic Mac OS historically used carriage return ("\r"), but that is not the normal environment for modern PHP.
Mini Project
Description
Build a small PHP command-line report generator. It creates a plain-text task report using PHP_EOL, so the report uses the native line-ending convention of the computer running the script.
Goal
Generate a task-report.txt file and print a readable completion message in the terminal.
Requirements
Requirement 1
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.