PHP — Reading streams with fgets
PHP fgets reads the next line from a stream. Use rewind after writing to read from the beginning, and compare the return value strictly with false when reading.
A simple example
Read back one letter
- Start with A
- Do this Write, then read
- Result A
<?php
$file = tmpfile();
fwrite($file, "A");
rewind($file);
echo fread($file, 1), PHP_EOL;
fclose($file);
A
Sum two lines from a temporary report
tmpfile returns a stream or false. rewind resets its position. fgets returns false at the end, so the strict comparison keeps a line containing the digit zero. Closing the resource removes the temporary file.
Morning staff record four returns in a file and afternoon staff record seven on the next line. Read each line as a number and add it to the running total. The day ends with eleven returns.
Run the example
PHP 8 or later. Run these commands from the directory containing the example.
php lesson.php
<?php
declare(strict_types=1);
$report = tmpfile();
if ($report === false) {
throw new RuntimeException('Could not open temporary file');
}
try {
fwrite($report, "4\n7\n");
rewind($report);
$total = 0;
while (($line = fgets($report)) !== false) {
$total += (int) trim($line);
}
echo $total, PHP_EOL;
} finally {
fclose($report);
}
11
The file contains two whole-number readings on separate lines. Reading from the beginning gives 4 and 7, for a total of 11. The example creates its own file, so it can run in a clean working directory.
Try it yourself
Add a third line containing 12.
Check your answer
The new total is 23. This report format assumes valid integer readings. When accepting external input, apply the validation techniques from the preceding lesson.