I/O Operations in PHP
Learn how to handle console output, read from standard input, and work with files in PHP using practical Docker-ready examples
Input and output are how a program communicates with the outside world — printing results to a terminal, reading what a user types, and persisting data to files. PHP was born as a web language, where “output” usually means generating an HTML response, but its command-line interface (CLI) exposes a full set of stream and filesystem functions that feel familiar to anyone coming from C or Perl.
Because PHP is a dynamic, weakly-typed language, its I/O functions are pragmatic and forgiving: most return a useful value on success and false on failure, and PHP will happily coerce numbers and strings as needed. This tutorial moves beyond the echo you saw in Hello World to cover formatted output, reading from standard input, writing and reading files, and handling I/O errors gracefully.
By the end you’ll be able to build small command-line tools that prompt for input, process data, and read or write files — all runnable in a container with nothing installed locally.
Formatted Output
Beyond echo, PHP provides printf/sprintf for C-style formatted output and direct access to the standard output and error streams through the predefined constants STDOUT and STDERR.
Create a file named output.php:
| |
The %s, %d, and %.2f placeholders map to string, integer, and fixed-precision float arguments. Writing to STDERR keeps diagnostic messages separate from real program output — important when a tool’s output is piped into another command.
Reading from Standard Input
The STDIN stream lets a CLI program read what the user types. fgets(STDIN) reads one line including the trailing newline, so wrapping it in trim() is the common idiom.
Create a file named input.php:
| |
When you pipe input into the program (as shown in the Docker section below), the prompts print without waiting, since the answers are supplied non-interactively.
Writing Files
PHP offers two levels of file writing: the one-shot file_put_contents() for when you have all the data at once, and the stream-based fopen/fwrite/fclose trio for incremental writes.
Create a file named write_file.php:
| |
The "w" mode truncates the file (or creates it); use "a" to append or "r" for read-only. Always call fclose() to flush buffered data and release the handle.
Reading Files
Reading mirrors writing. file_get_contents() slurps an entire file into a string, file() returns an array of lines, and fgets() in a loop reads one line at a time — the memory-efficient choice for large files.
Create a file named read_file.php:
| |
The fgets() loop uses !== false (strict comparison) because a line containing only "0" would be falsy — a classic PHP gotcha that strict comparison avoids.
Handling I/O Errors
Filesystem operations can fail: a path may not exist, or permissions may be wrong. PHP’s older functions emit a warning and return false, while modern code often wraps failures in exceptions for structured handling.
Create a file named io_errors.php:
| |
Checking the return value is essential — because PHP is forgiving, an unchecked false can silently propagate through the rest of your program.
Running with Docker
| |
Expected Output
Running output.php:
Standard output line
Name: Ada, Age: 36
Pi is approximately 3.14
00042
Written to STDOUT
Written to STDERR
Running input.php with the piped input Ada and 36:
What is your name? How old are you? Hello, Ada! Next year you will be 37.
Running write_file.php:
Files written successfully
Running read_file.php:
Full contents:
apple
banana
cherry
Line count: 3
Numbered lines:
1: apple
2: banana
3: cherry
Running io_errors.php:
Error: could not read nonexistent/data.txt
Caught: Unable to open nonexistent/data.txt
Program continues after handling the error
Key Concepts
echovsprintf—echooutputs strings verbatim, whileprintf(and its string-returning siblingsprintf) apply C-style format specifiers like%s,%d, and%.2f.- Predefined stream constants — the CLI exposes
STDIN,STDOUT, andSTDERRas ready-to-use file handles; sending diagnostics toSTDERRkeeps them out of piped output. - Two ways to read and write — one-shot helpers (
file_get_contents,file_put_contents,file) are concise, while thefopen/fread/fwrite/fclosestream API scales to large files and gives incremental control. - File modes matter —
"r"reads,"w"truncates-or-creates, and"a"appends; theFILE_APPENDflag adds tofile_put_contentswithout a handle. - Check return values strictly — I/O functions return
falseon failure, so use=== false/!== falseto avoid PHP’s weak-typing traps (a line of"0"is falsy but valid data). trim()on input —fgets(STDIN)keeps the trailing newline; trimming before use is the standard idiom for reading typed input.- Two error styles — legacy functions emit warnings and return
false(suppress with@and check manually), while modern code throws exceptions caught withtry/catchfor structured recovery.
Running Today
All examples can be run using Docker:
docker pull php:8.4-cli-alpine
Comments
Loading comments...
Leave a Comment