Example 1 — Read Characters One by One
Create a tiny file and print each character with a bar after it.
<?php
$path = sys_get_temp_dir() . '/codetofun_fgetc.txt';
file_put_contents($path, 'Hi!');
$handle = fopen($path, 'r');
while (($char = fgetc($handle)) !== false) {
echo $char, '|';
}
echo PHP_EOL;
fclose($handle);
unlink($path); How It Works
- file_put_contents() creates a file that contains the three characters Hi!.
- fgetc() returns the next character each time it is called.
- The !== false check keeps the loop running until the end of the file.
- Each character is printed followed by a bar, so you can see them one by one.

