Coding/Learn/php/php file system and streams
PHP Foundational Course
01.Introduction, Server-Side Architecture & Syntax
02.Variables, Strict Types & Dynamic Casting
03.Strings, Numbers & Built-in Math Functions
04.Operators, Null Coalescing & Magic Constants
05.Control Flow: If-Else, Switch & Modern Match Expressions
06.Loops: While, For & Foreach Traversal
07.Functions, Type Declarations & Named Arguments
08.Arrays & Functional Array Manipulation
09.Superglobals, Form Handling & Input Sanitization
10.Date, Time & DateTimeImmutable Objects
11.File System, Streams & I/O Operations
12.Cookies, Sessions & State Management
13.Exceptions, Throwables & Custom Error Fences
14.Classes, Objects & Constructor Property Promotion
15.Inheritance, Access Modifiers & Method Overriding
16.Interfaces, Abstract Classes & Polymorphism
17.Traits, Static Members & Namespaces
18.PDO, MySQL & Prepared Statements against SQL Injection
19.JSON & XML REST API Interoperability
20.Capstone: Production Secure Backend API & User Registry Engine
Course Certificate0%

Complete all lessons to earn

LearnFile System, Streams & I/O Operations
11 / 20 0%
Lesson 11 of 20
9 mins read

File System, Streams & I/O Operations

PreviousNext Lesson
In Plain English

PHP excels at file system manipulation. Master high-level one-liners (file_get_contents, file_put_contents) and streaming low-level resource handlers (fopen, fread, fwrite, fclose, flock) for memory-efficient processing of large logs and files.

The Mental Model

"file_get_contents is like reading an entire book into your memory in one second. fopen and fgets are like reading the book line-by-line with a magnifying glass without filling your desk."

Deep Dive: How It Works

One-Line Helpers: file_get_contents($path) reads entire file to string; file_put_contents($path, $data, FILE_APPEND) writes data.

Stream Resources: fopen($path, "r"|"w"|"a") opens a stream handle.

Memory Efficiency: Streaming with while (!feof($h)) fgets($h) reads gigabyte-sized log files with almost zero RAM usage.

Filesystem Checks: file_exists(), is_readable(), is_writable(), and filesize().

Syntax Blueprint

<?php

file_put_contents("app.log", "Event logged\n", FILE_APPEND);
$content = file_get_contents("app.log");
$exists = file_exists("app.log");

Use file_put_contents with FILE_APPEND to write logs, and file_get_contents to read files.

PointCore Rules to Remember

Point star
Atomic Writes: file_put_contents($path, $data, LOCK_EX) obtains an exclusive lock to prevent write races.
Point star
Always Close Streams: Always call fclose($handle) when using low-level fopen to free file descriptors.
Point star
URL Stream Wrappers: file_get_contents("https://...") can fetch remote HTTP responses if allow_url_fopen is enabled.

Common Beginner Traps & How to Fix Them

Mistake:Loading a 2GB log file with file_get_contents() and exceeding memory_limit.

Why it happens: file_get_contents buffers the entire file into PHP memory at once.

How to fix: Use fopen() with a while (!feof($handle)) fgets($handle) line-by-line stream loop.

Pro Tip: Use __DIR__ . "/path/to/file" to ensure file paths resolve reliably regardless of current working directory.

Live Interactive Example

Hit Run Code to see it live
In-Memory Stream Reading and Writing
PHP 8.2 / CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Output Console
Click "Run Code" to view the rendered output.
How it works: php://memory provided a fast in-memory stream buffer, rewound and read with fgets.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Simulate Log Line Generation

  • PointOpen an in-memory stream $stream = fopen("php://memory", "r+").
  • PointWrite "STATUS_OK: System nominal\n" into the stream.
  • PointRewind the stream with rewind($stream).
  • PointRead the content using stream_get_contents($stream) and echo it.
  • PointClose the stream with fclose($stream).
1
2
3
4
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates