Skip to content

Chapter 15 of 38

File Handling

Open, read, write, lock, stream, and safely resolve filesystem paths.

42 minutes 10 quick checksBy Subha Prasad
Lesson 15 of 38Course navigation

Lesson content

Read, practise, then check your understanding

PHP streams unify files and other sources. Modes control reading, append, truncation, creation, and binary semantics. Every failure and partial write must be handled.

Practical example

<?php
$handle = fopen($path, 'xb');
if ($handle === false) throw new RuntimeException('open failed');
try { if (!flock($handle, LOCK_EX) || fwrite($handle, $data) === false) throw new RuntimeException('write failed'); }
finally { fclose($handle); }

Never concatenate raw user paths into privileged roots. Constrain resolved paths, permissions, sizes, and symlink behavior. Stream large data. Important replacement often writes a temporary sibling and renames it atomically where supported.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes fopen?
Which PHP term matches this description: Opening a stream resource in a selected mode.
Which statement best describes fread?
Which PHP term matches this description: Reading a specified byte count from a stream.
Which statement best describes fwrite?
Which PHP term matches this description: Writing bytes to a stream.
Which statement best describes flock?
Which PHP term matches this description: Advisory file locking where supported.
Which statement best describes stream wrapper?
Which PHP term matches this description: A uniform URI-style interface for files and other data sources.

0 of 10 checks passed

Your progress is saved on this device.