What are common issues encountered when using readfile for file downloads in PHP?
One common issue when using readfile for file downloads in PHP is that it may not handle large files efficiently, potentially causing memory exhaustion. To solve this, you can use a combination of readfile and output buffering to stream the file in chunks, rather than loading the entire file into memory at once.
$file = 'path/to/file.zip';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-Length: ' . filesize($file));
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
ob_clean();
flush();
readfile($file);
exit;
} else {
echo 'File not found';
}
Keywords
Related Questions
- How can one properly define and include JavaScript from an external source in PHP?
- What are some best practices for handling premature loop termination in PHP, specifically in the context of foreach loops?
- What potential pitfalls should a PHP beginner be aware of when trying to create a text file using PHP?