Accessing Standard Input in PHP
PHP is notoriously optimized for web server environments where stdin rarely exists. In a typical HTTP request, data arrives via POST bodies or query strings, and output goes straight to the browser. However, when leveraging PHP as a general-purpose scripting languageâoften invoked from command-line interfaces (CLI) or cron jobsâit is entirely possible to read from standard input. This capability relies on the underlying operating system's file descriptor handling rather than any specific PHP magic.
The most direct way to access stdin in PHP is by opening the special file /dev/stdin. On Unix-like systems, this path represents a link to the terminal or pipe that feeds data into the running process. You can treat this input stream exactly like any other file handle using standard I/O functions such as fopen(), fgets(), fgetc(), or stream_get_contents().
Here is a practical example using fopen() and fgets() to read lines from standard input:
<?php
// Open the standard input stream
$handle = fopen('/dev/stdin', 'r');
if ($handle) {
echo "Reading from stdin...\n";
// Read a single line
$line = fgets($handle);
if ($line !== false) {
echo "Input received: " . trim($line) . "\n";
// You can loop to read multiple lines until EOF or Ctrl+D/Z
while (($line = fgets($handle)) !== false) {
// Process each line here
}
} else {
echo "No data received.\n";
}
fclose($handle);
} else {
echo "Failed to open /dev/stdin\n";
}
Using fopen('/dev/stdin', 'r') is the most portable approach across Linux and macOS. It abstracts the underlying file descriptor logic into a familiar PHP stream wrapper interface. This method allows you to leverage existing error handling, buffering controls, and stream context options if needed. For instance, you can set read timeouts or adjust buffer sizes using stream_context_create() before opening the handle, just as you would for remote HTTP resources.
If you prefer not to deal with file descriptors explicitly, the php://stdin stream wrapper offers an alternative syntax that behaves similarly but avoids hardcoding the device path:
<?php
$handle = fopen('php://stdin', 'r');
$data = stream_get_contents($handle);
echo $data;
fclose($handle);
This approach is functionally equivalent to /dev/stdin on most systems and integrates seamlessly with functions like stream_get_contents(). It is particularly useful when you want to read the entire input until the end-of-file (EOF) marker without managing a loop manually.
Testing from the Terminal
To verify that your script works, you need to pipe data into it. From your terminal, use the shell pipe operator | to send text directly to PHP:
echo -e "Hello\nWorld" | php stdin_test.php
In this scenario, /dev/stdin becomes a pipe connected to the output of the previous command. The PHP script reads from this stream exactly as if it were a regular file. On Windows, the mechanism differs slightly; php://stdin is generally preferred over hardcoded paths because Windows does not universally expose /dev/stdin.
Important Considerations
The primary pitfall when working with standard input in PHP is buffering. By default, PHP buffers output and sometimes input to improve performance, especially in web contexts. When reading from stdin interactively or via a pipe, unexpected buffering can cause your script to hang waiting for data that the user never sent because they didn't signal EOF (Ctrl+D on Unix, Ctrl+Z then Enter on Windows).
Additionally, ensure your PHP binary is being run in CLI mode. If you invoke the script via an Apache module like mod_php, /dev/stdin might not be accessible or may point to the wrong location depending on the server configuration. Always check your execution environment before assuming stdin behaves as expected.
For complex streaming applications where line buffering interferes with real-time processing, consider opening the stream in non-blocking mode or adjusting the buffer size using stream_set_blocking() and stream_set_chunk_size(). These settings allow you to fine-tune how PHP interacts with the underlying OS pipe, ensuring your script responds efficiently regardless of the input source.