readfile(), file_get_contents())PHP provides simple high-level functions for inspecting files, checking file existence, reading file contents into memory strings, and piping file streams directly to the HTTP output response.
file_exists($path): Returns true if file or directory exists.is_file($path): Returns true if target path is a regular file.filesize($path): Returns file size in bytes.readfile($path): Reads file and writes content directly to output buffer (ideal for downloads).file_get_contents($path): Reads entire file content into a PHP string variable.flowchart TD
A["File System Path Check"] --> B{"file_exists($file)"}
B -- False --> C["Return File Not Found Error"]
B -- True --> D{"Choose Read Strategy"}
D -- Memory String --> E["$content = file_get_contents($file)"]
D -- Direct Stream Download --> F["readfile($file)"]
<?php
declare(strict_types=1);
$filePath = __DIR__ . '/sample_log.txt';
// Create temporary sample file if not present
if (!file_exists($filePath)) {
file_put_contents($filePath, "2026-08-13 10:00:00 | SYSTEM_INIT | Service started successfully.
");
}
// 1. File Inspection
if (file_exists($filePath) && is_file($filePath)) {
$bytes = filesize($filePath);
echo "Target File: " . basename($filePath) . " ($bytes bytes)
";
// 2. Reading entire file content into string
$fileData = file_get_contents($filePath);
echo "--- File Contents ---
" . $fileData;
} else {
echo "Error: Target file does not exist.
";
}
file_exists() Before Reading: Always verify file existence to avoid E_WARNING file access errors.file_get_contents() for Small-to-Medium Files: Simple and fast for reading files under a few megabytes into memory strings.file_get_contents(); stream them line-by-line using fopen() and fgets().Write a PHP script that checks if config.json exists using file_exists(), and if so, reads its content into $jsonString using file_get_contents()!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.