What are the limitations of using readfile() for downloading images in PHP, especially in terms of file size?

When using readfile() to download images in PHP, one limitation is that it loads the entire file into memory before sending it to the client, which can be inefficient for large files and may lead to memory exhaustion. To overcome this limitation, it is recommended to use a combination of fopen(), fread(), and fpassthru() functions to read and output the file in smaller chunks, thus reducing memory usage.

<?php
$file = 'image.jpg';

header('Content-Description: File Transfer');
header('Content-Type: image/jpeg');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));

$handle = fopen($file, 'rb');
while (!feof($handle)) {
    echo fread($handle, 8192);
}
fclose($handle);