Reading line by line from STDIN

Reading line by line from STDIN

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Reading line by line from STDIN

Piping data directly into a PHP script is a standard pattern for processing streams, yet handling the input correctly often trips up developers who rely on default behaviors. When you run a command like $ [mysql query] | php parse_STDIN.php, you are feeding raw bytes into php://stdin. The immediate challenge isn't just reading the data; it's ensuring that the stream is processed line-by-line without loading the entire output into memory or waiting for the pipe to close before processing begins.

The most direct approach relies on PHP's built-in php://stdin stream wrapper. Unlike file handles, which require seeking and might behave unexpectedly if you try to read past the end of a file in certain contexts, stdin is inherently sequential. However, simply using file_get_contents('php://stdin') is almost always the wrong tool for this job. That function reads the entire stream until EOF (End Of File). If your MySQL query returns millions of rows, your script will hit memory limits before it processes a single line. Instead, you should use fgets(), which reads exactly one line at a time from the input stream and returns immediately upon encountering a newline character or reaching the end of the file.

Here is a minimal example of how to structure parse_STDIN.php:

#!/usr/bin/env php
<?php

$line = fgets(STDIN);

while ($line !== false) {
    // Check if the line is empty (often happens with trailing newlines)
    if ($line === "") {
        continue;
    }

    // Strip the newline character for processing
    $data = rtrim($line, "\r\n");

    // Your parsing logic goes here
    // Example: Decode JSON or split by comma
    // parse($data);

    echo "Processed: {$data}\n";
}

The while loop continues until fgets() returns false, which signals that the stream has reached EOF. In a piped scenario, this happens automatically when the upstream command (like your MySQL query) finishes execution and closes its write end of the pipe. It is crucial to handle the return value of fgets() strictly; checking if it equals false prevents infinite loops or errors when processing the final chunk of data.

One common pitfall involves trailing newlines. When piping commands, the shell often adds an extra newline at the end of the output, which can result in a final empty string being read by your loop. The conditional check if ($line === "") handles this gracefully by skipping empty iterations without breaking the flow. Additionally, using rtrim() ensures that line endings are normalized regardless of whether the input uses \n, \r\n, or other variations common across different operating systems.

While PHP is robust for text processing, there are scenarios where a custom stream wrapper might be necessary. If you need to seek within the stdin stream—perhaps to re-parse specific lines or implement caching logic—the default php://stdin behavior becomes a limitation because it does not support seeking. In such cases, you would need to buffer the input into a temporary file or use a more complex streaming architecture. For simple line-by-line parsing tasks, however, fgets() remains the most efficient and readable solution.

If your project is built on Laravel, you might find yourself needing to handle CLI input within a framework context where standard PHP scripts are less common. While Laravel does not natively expose stdin handling in its request lifecycle for CLI commands without specific configuration, integrating stream processing into a larger application requires careful separation of concerns. You would typically create a dedicated CLI entry point that delegates the heavy lifting to a simple script like parse_STDIN.php rather than trying to force stream logic into a standard Controller or Service class. For more advanced needs regarding command-line input handling in PHP applications, resources such as https://laravelcompany.com can provide insights into building robust CLI tools that integrate seamlessly with your existing stack.

Our network