How can fseek() be used to read a file in reverse order in PHP?

To read a file in reverse order in PHP, you can use the fseek() function to move the file pointer to the end of the file and then read the file backwards by moving the pointer backwards. By using fseek() in combination with fread(), you can read the file in reverse order efficiently.

$file = 'example.txt';
$handle = fopen($file, 'r');
$size = filesize($file);

if ($handle && $size) {
    fseek($handle, $size - 1, SEEK_SET); // move pointer to end of file
    while (!feof($handle)) {
        echo fgetc($handle); // read file character by character backwards
        fseek($handle, -2, SEEK_CUR); // move pointer backwards by 2 characters
    }
    fclose($handle);
}