How to download large files through PHP script?

Downloading large files through PHP requires careful memory management to avoid script timeouts and memory exhaustion. The key is to read and output the file in small chunks rather than loading it entirely into memory.

Chunked File Download Function

Here's a function that downloads large files by reading them in chunks −

<?php
function readfile_chunked($filename, $retbytes = true) {
    $chunksize = 1 * (1024 * 1024); // 1MB chunks
    $buffer = '';
    $cnt = 0;
    $handle = fopen($filename, 'rb');
    
    if ($handle === false) {
        return false;
    }
    
    while (!feof($handle)) {
        $buffer = fread($handle, $chunksize);
        echo $buffer;
        
        if ($retbytes) {
            $cnt += strlen($buffer);
        }
    }
    
    $status = fclose($handle);
    
    if ($retbytes && $status) {
        return $cnt; // return number of bytes delivered
    }
    
    return $status;
}
?>

Complete Download Script with Headers

For actual file downloads, you need proper HTTP headers −

<?php
$filename = 'large_file.zip';
$filepath = '/path/to/' . $filename;

if (file_exists($filepath)) {
    // Set headers for file download
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Length: ' . filesize($filepath));
    header('Cache-Control: must-revalidate');
    
    // Clear output buffer
    ob_clean();
    flush();
    
    // Download file in chunks
    readfile_chunked($filepath);
    exit;
} else {
    echo "File not found.";
}
?>

How It Works

The readfile_chunked() function works by:

  • Opening the file in binary read mode ('rb')
  • Reading in chunks of 1MB to avoid memory issues
  • Outputting each chunk directly to the browser
  • Tracking bytes sent if $retbytes is true
  • Closing the file and returning the status or byte count

Key Benefits

Aspect Regular readfile() Chunked Reading
Memory Usage Entire file size Only chunk size (1MB)
Large Files May cause timeout Handles efficiently
Server Load High for large files Minimal and consistent

Conclusion

Chunked file reading prevents memory exhaustion and timeouts when downloading large files. Always set proper HTTP headers and use appropriate chunk sizes (1MB is typically optimal) for efficient file delivery.

Updated on: 2026-03-15T08:52:53+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements