Reading & Writing Files
PHP has dozens of file functions — from simple file_get_contents to fine-grained fopen/fread/fwrite for large files. Choosing the right approach depends on file size, whether you need streaming, and error handling requirements. For small files, one-liner functions suffice; for large files or network streams, handle buffered reading.
File Reading, Writing & Error Handling
<?php
declare(strict_types=1);
// ── Simple reads ──────────────────────────────────────────────
// file_get_contents — reads entire file into string (up to ~50MB safely)
$content = file_get_contents("/var/www/html/storage/posts/php-basics.md");
if ($content === false) {
throw new RuntimeException("Could not read file.");
}
// file — reads into array of lines (each line is an element)
$lines = file("/path/to/data.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// Read only N bytes (header sniffing, configuration snippets)
$handle = fopen("/path/to/large.log", "rb");
if ($handle === false) throw new RuntimeException("Cannot open log file.");
$firstLine = fgets($handle); // read one line
fclose($handle);
// ── Simple writes ─────────────────────────────────────────────
// file_put_contents — optimal for full overwrites
$bytesWritten = file_put_contents(
"/var/www/html/storage/cache/homepage.html",
$renderedHtml,
LOCK_EX // lock file during write — prevents concurrent corruption
);
// Append to an existing file
file_put_contents(
"/var/www/html/storage/logs/app.log",
date("[Y-m-d H:i:s] ") . "Post published: php-basics
",
FILE_APPEND | LOCK_EX
);
// ── fopen — fine-grained control (large files, line-by-line) ──
$source = fopen("/storage/exports/posts.csv", "rb") ?: throw new RuntimeException("Cannot open.");
$destination = fopen("/storage/exports/posts_backup.csv", "wb") ?: throw new RuntimeException("Cannot create.");
// Copy in 8KB chunks — never loads full file into RAM
while (!feof($source)) {
$chunk = fread($source, 8192);
fwrite($destination, $chunk);
}
fclose($source);
fclose($destination);
// ── Directory operations ──────────────────────────────────────
// Create directory (with parents) if not exists
$uploadDir = "/var/www/html/storage/uploads/" . date("Y/m");
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true); // recursive
}
// List directory contents
$iterator = new DirectoryIterator("/var/www/html/storage/logs");
foreach ($iterator as $file) {
if ($file->isDot() || !$file->isFile()) continue;
echo $file->getFilename() . " — " . $file->getSize() . " bytes
";
}
// ── SplFileInfo — OOP file info ───────────────────────────────
$info = new SplFileInfo("/var/www/html/public/index.php");
echo $info->getFilename(); // "index.php"
echo $info->getExtension(); // "php"
echo $info->getSize(); // bytes
echo $info->getMTime(); // last modified Unix timestamp
echo $info->getPathname(); // full path
// ── Temporary files ───────────────────────────────────────────
$tmpFile = tempnam(sys_get_temp_dir(), "blog_");
file_put_contents($tmpFile, $processedData);
// ... process ...
unlink($tmpFile); // always clean up!Quick Quiz
Tip
Tip
Practice Reading Writing Files in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
PHP processes each request through the server-side engine
Practice Task
Note
Practice Task — (1) Write a working example of Reading Writing Files from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Reading Writing Files is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.