File Handles, Streams and Wrappers

4.File Handles, Streams and Wrappers

M

In this chapter

We'll learn how file handles let PHP read and write a file piece by piece with fopen(), fgets() and fwrite(), what each fopen() mode does, what a stream is and how wrappers like php://, http:// and data:// let the same functions work on memory, the network and the request body, and how command-line scripts use standard input, output and error.

17–19 min

The Problem in Real Life

Olivia asks how many booking pages were opened yesterday. The web server's access log is 2.1 GB. Mia writes count(file('/var/log/nginx/access.log')) and the script dies: "Allowed memory size of 134217728 bytes exhausted" — file() tried to put 2.1 GB of lines into memory at once.

Marcus rewrites it in four lines that read one line at a time. The script uses less than 1 MB of memory and finishes in seconds.

M

You don't need the whole river in a bucket. You need a tap.

Marcus

Loading Everything at Once vs. Reading a Stream

Memory limits

file() and file_get_contents() load the whole file. Big files don't fit.

A handle and a position

fopen() gives a handle; each fgets() reads the next line from where the last one stopped.

One API, many sources

Files, memory, the request body and URLs are all streams with the same functions.

File Handles, Streams and Wrappers

Reading and writing piece by piece: chapter 2's functions handle whole files. Streams handle data of any size, from any source, a piece at a time. This chapter covers:

  • File handles: fopen(), modes, fgets(), fwrite() and fclose().
  • Streams: what they are and why they save memory.
  • Wrappers: file://, php://, http:// and data://.
  • php://input, memory and temp: the request body and in-memory files.
  • Standard input, output and error: streams for terminal scripts.

File handles: fopen($path, $mode) opens a file and returns a handle — a value of type resource that remembers which file is open and the current position in it. Then fgets($handle) reads the next line, fread($handle, 8192) the next 8 KB, and fwrite($handle, $text) writes at the position, moving it forward. feof($handle) tells whether the end is reached; ftell() gives the position, and fseek() / rewind() move it. fclose($handle) closes the file — PHP closes handles automatically at the end of the request, but closing early releases locks (chapter 6). Every read function returns false at the end or on failure, so the classic loop is while (($line = fgets($handle)) !== false).

Reading line by line with a handle
<?php
$log = '/tmp/access.log';
file_put_contents($log, implode("\n", [
'GET /book.php 200',
'GET /prices.php 200',
'GET /book.php 500',
'POST /book.php 302',
]) . "\n");
$handle = fopen($log, 'r');
$bookingPages = 0;
while (($line = fgets($handle)) !== false) { // one line at a time
if (str_contains($line, '/book.php')) {
$bookingPages++;
}
}
fclose($handle);
echo "booking page requests: {$bookingPages}\n";
// booking page requests: 3

Modes: the second argument of fopen() says what you want to do, and the wrong one destroys data. 'r' reads; 'w' writes but empties the file immediately on opening; 'a' appends; 'x' creates a new file and fails if it exists; 'c' opens for writing without emptying — the mode for locking before changing (chapter 6). Adding + allows both reading and writing. The table below lists them all.

Table — fopen() modes
ModeReadWriteStarts atIf the file existsIf it doesn't
rYesNoBeginningOpens itFails
r+YesYesBeginningOpens itFails
wNoYesBeginningEmpties it at onceCreates it
w+YesYesBeginningEmpties it at onceCreates it
a / a+No / YesYes, always at the endEndOpens itCreates it
x / x+No / YesYesBeginningFailsCreates it
c / c+No / YesYesBeginningOpens it, keeps the contentCreates it

Streams: a stream is any source or destination of bytes that can be read or written in order: a file, a network connection, the request body, a piece of memory. PHP's file functions — fopen(), fgets(), fwrite(), even file_get_contents() — all work on streams. Because a stream is read a piece at a time, the memory used stays the same whatever the size: one line of the 2.1 GB log at a time. That's the fix for Olivia's question. SplFileObject wraps the same thing in an object you can loop over with foreach. The diagram below compares the two approaches.

Counting lines in a 2.1 GB log

count(file($log))

reads all 2.1 GB into an array

while (($line = fgets($h)) !== false)

reads one line, then the next

memory

Memory: the whole file

→ "Allowed memory size exhausted"

Memory: one line

→ under 1 MB, any file size

The same with SplFileObject
<?php
file_put_contents('/tmp/access.log', "GET /book.php 200\nGET /prices.php 200\nGET /book.php 500\n");
$file = new SplFileObject('/tmp/access.log');
$file->setFlags(SplFileObject::DROP_NEW_LINE | SplFileObject::SKIP_EMPTY | SplFileObject::READ_AHEAD);
foreach ($file as $number => $line) {
echo $number + 1, ": ", $line, "\n";
}
// 1: GET /book.php 200
// 2: GET /prices.php 200
// 3: GET /book.php 500

Wrappers: the part before :// in a path chooses a wrapper — the code that knows how to talk to that kind of stream. Plain paths use file://. http:// and https:// read a URL, so file_get_contents('https://…') downloads a page (for real APIs, use an HTTP client like Guzzle, Act 16). data:// reads data written in the string itself. php:// gives PHP's own special streams (below). stream_get_wrappers() lists what your PHP supports, and libraries can register their own — that's how some packages read files from cloud storage with the normal functions.

Wrappers: one function, different sources
<?php
print_r(stream_get_wrappers()); // what this PHP supports
echo file_get_contents('data://text/plain,Hello from a data stream'), "\n";
echo file_get_contents('data://text/plain;base64,' . base64_encode('BookBay')), "\n";
// Array ( [0] => php [1] => file [2] => glob [3] => data [4] => http [5] => https … )
// Hello from a data stream
// BookBay

php://input, php://memory and php://temp: php://input is the raw body of the current HTTP request. When a mobile app sends JSON, $_POST stays empty — PHP only fills it for forms — and json_decode(file_get_contents('php://input'), true) reads the data (Act 16). php://output writes to the same place as echo. php://memory is a stream that lives only in memory, and php://temp starts in memory and moves to a temporary file once it grows past 2 MB. They're perfect for building a CSV in memory before sending it, or for testing code that expects a file.

php://memory, and reading a JSON request body
<?php
$buffer = fopen('php://memory', 'r+'); // a file that lives in memory
fwrite($buffer, "id,customer\n4811,Tom Hart\n");
rewind($buffer); // back to the start before reading
echo stream_get_contents($buffer);
fclose($buffer);
// In a real API endpoint (Act 16), the JSON body is read like this:
// $data = json_decode(file_get_contents('php://input'), true, flags: JSON_THROW_ON_ERROR);
// $_POST is empty for JSON requests — PHP fills it only for form data.
// id,customer
// 4811,Tom Hart

Standard input, output and error: every command-line program has three streams: standard input (what's typed or piped in), standard output (normal results) and standard error (messages and errors). In PHP's CLI they're ready as the constants STDIN, STDOUT and STDERR — and as php://stdin, php://stdout, php://stderr everywhere. Writing errors to STDERR keeps them out of the results: php bin/export.php > bookings.csv puts the CSV in the file and still shows errors on screen. The constants exist only in the CLI; the PHP Playground doesn't have them.

A terminal script with STDIN, STDOUT and STDERR (run on your computer)
<?php
// bin/remind.php — reads names from standard input
while (($line = fgets(STDIN)) !== false) {
fwrite(STDOUT, "reminder for " . trim($line) . "\n");
}
fwrite(STDERR, "done\n");
// $ printf 'Tom Hart\nAnn Lee\n' | php bin/remind.php > sent.txt
// done
// $ cat sent.txt
// reminder for Tom Hart
// reminder for Ann Lee

Streams in other languages: Java has InputStream / Reader classes and BufferedReader.readLine(), Node.js has stream objects with events, Python file objects are iterable line by line. Python's with open(...) and Java's try-with-resources close the file automatically at the end of a block; PHP doesn't support that syntax (Act 14) — close in finally, or rely on PHP closing handles when the request ends.

Key Takeaway

fopen() returns a handle (a resource) with a position; fgets(), fread() and fwrite() work from that position, and loops test fgets() !== false. Modes matter: r reads, w empties the file on opening, a appends, x creates only, c opens without emptying (for locking), and + adds the other direction. A stream is any byte source read piece by piece, so memory stays constant even for a 2 GB file. Wrappers select the source: file://, http(s)://, data://, php://. php://input is the raw request body (JSON APIs), php://memory and php://temp are in-memory files, and CLI scripts use STDIN, STDOUT and STDERR. PHP has no with/using block — close handles in finally.

Why This Matters

Streams are how PHP handles anything bigger than memory: logs, exports, imports, downloads. "Read it all, then process it" works in testing with ten rows and fails in production with ten million.

php://input is also the doorway to every JSON API you'll build — Laravel's $request->json() reads it for you — and STDIN/STDOUT/STDERR are how PHP's command-line tools play well with others.

The log counter runs in under 1 MB, whatever the file size. Next, Olivia wants the week's bookings as a spreadsheet for her accountant, and the SMS provider sends its delivery reports as XML. Mia's first CSV breaks in Excel the moment a customer's note contains a comma. That's the next chapter: CSV, JSON and XML files.