fopen(), fread(), fgets(), & fclose()For precise control over file I/O operations and handling large files line-by-line, PHP provides low-level file handle stream operations via fopen(), fread(), fgets(), feof(), and fclose().
fopen() Access Modes'r': Read only; pointer at beginning of file.'r+': Read and write; pointer at beginning of file.'w': Write only; truncates file to zero length or creates file.'a': Append only; pointer at end of file.flowchart TD
A["Open File Handle: fopen($path, 'r')"] --> B{"Check $handle !== false"}
B -- Error --> C["Handle Failed to Open Error"]
B -- Success --> D["Loop while (!feof($handle))"]
D --> E["Read Single Line: fgets($handle)"]
E --> D
D -- End of File --> F["Close Handle: fclose($handle)"]
<?php
declare(strict_types=1);
$logFile = __DIR__ . '/app.log';
// Generate mock log lines if missing
if (!file_exists($logFile)) {
file_put_contents($logFile, "LINE 1: User Login
LINE 2: DB Query
LINE 3: Logout
");
}
// Open file handle in read-only mode ('r')
$handle = fopen($logFile, 'r');
if ($handle === false) {
die("Fatal Error: Could not open file '$logFile' for reading.");
}
echo "--- Line-by-Line File Processing ---
";
$lineNumber = 1;
// Loop until End-Of-File (feof)
while (!feof($handle)) {
$line = fgets($handle); // Reads up to newline character
if ($line !== false) {
echo "Line #$lineNumber: " . trim($line) . "
";
$lineNumber++;
}
}
// Always close open handles to free system file descriptors!
fclose($handle);
fopen() with fclose(): Forgetting to close file handles leaks file descriptors and locks file resources on the operating system.fgets() for Memory-Efficient Line Parsing: Reading log files line-by-line keeps memory footprint minimal regardless of file size.$handle !== false before invoking reading methods.Write a while (!feof($handle)) loop that uses fgets() to count the total number of lines in a text file!
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.