Current Location: Home> Latest Articles> Detailed Guide to Implementing File Downloads in PHP Using Three Methods

Detailed Guide to Implementing File Downloads in PHP Using Three Methods

gitbox 2025-08-04

Implementing File Downloads in PHP Using Three Methods

File downloading is a common requirement in web development. PHP offers multiple ways to achieve this functionality. This article will introduce three widely used and practical methods for PHP file downloads, helping developers apply them flexibly based on their specific needs.

Direct Output of File Content

The simplest way to handle file downloads is by using the readfile() function to read and output the file. By setting appropriate HTTP headers, the browser can correctly process the download request.


$filename = 'path/to/file.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
readfile($filename);

This code sets the Content-Type header to specify the file MIME type and Content-Disposition to instruct the browser to treat it as an attachment for download. The readfile() function reads and outputs the file content.

Using file_get_contents() to Read File Content

Another approach is to read the file into memory first using file_get_contents(), then output it to the client. This method works well for small to medium-sized files.


$filename = 'path/to/file.pdf';
$filecontent = file_get_contents($filename);
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
echo $filecontent;

This is similar to readfile(), but reads the file content into a variable before sending it with echo.

Using fread() to Read Large Files in Chunks

For large files, it is recommended to read and output the file in chunks using fread() to avoid high memory usage.


$filename = 'path/to/largefile.zip';
$chunkSize = 1024 * 1024; // 1MB
$handle = fopen($filename, 'rb');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
while (!feof($handle)) {
    echo fread($handle, $chunkSize);
    ob_flush();
    flush();
}
fclose($handle);

This code loops to read the file in specified chunk sizes, using ob_flush() and flush() to immediately send output to the client. This approach helps reduce memory consumption during large file downloads.

Summary

The three PHP file download methods introduced here each have their own advantages: direct output with readfile() is straightforward and suitable for small files; using file_get_contents() is appropriate for medium-sized files; chunked reading with fread() is ideal for large files and efficiently controls memory usage. Choosing the right method based on your project's needs can improve download performance and user experience.