PHP Instance code that failed to download large files and limited download speed

  • 2021-12-11 07:14:27
  • OfStack

1. Issues:

When PHP uses readfile function to define downloading files, the files should not be too large, otherwise the downloading will fail, the files will be damaged and no errors will be reported;

2. Reason:

This is because readfile will put the file into the cache when reading the file, resulting in memory overflow;

3. Solution: Download in sections and limit the download speed;


<?php
// Set the maximum file execution time 
set_time_limit(0);

if (isset($_GET['filename']) && !empty($_GET['filename'])) {
  $file_name = $_GET['filename'];
  $file = __DIR__ . '/assets/' . $file_name;
} else {
  echo 'what are your searching for?';
  exit();
}

if (file_exists($file) && is_file($file)) {
  $filesize = filesize($file);
  header('Content-Description: File Transfer');
  header('Content-Type: application/octet-stream');
  header('Content-Transfer-Encoding: binary');
  header('Accept-Ranges: bytes');
  header('Expires: 0');
  header('Cache-Control: must-revalidate');
  header('Pragma: public');
  header('Content-Length: ' . $filesize);
  header('Content-Disposition: attachment; filename=' . $file_name);

  //  Open a file 
  $fp = fopen($file, 'rb');
  //  Set pointer position 
  fseek($fp, 0);

  //  Open buffer 
  ob_start();
  //  Read files in sections 
  while (!feof($fp)) {
    $chunk_size = 1024 * 1024 * 2; // 2MB
    echo fread($fp, $chunk_size);
    ob_flush(); //  Refresh PHP Buffer to Web Server 
    flush(); //  Refresh Web Server buffer to browser 
    sleep(1); //  Every 1 Seconds   Download  2 MB
  }
  //  Close buffer 
  ob_end_clean();
  fclose($fp);
} else {
  echo 'file not exists or has been removed!';
}
exit();

Summarize


Related articles: