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);
Keywords
Related Questions
- How can the DateTime class in PHP be used to calculate average times from a set of decimal values and convert them to the format 00:00:00?
- What are the potential consequences of having multiple HTML head sections in a PHP script?
- What is the purpose of the script and what is currently happening with the user data storage?