PHP实现文件下载限速的方法

xiao5788-xsi / 2024-03-17 / 原文

/**

  • 下载文件并限速

  • @param string $file_path 文件路径

  • @param int $kilobytes 每秒下载的 KB 数
    */
    function downloadFileWithSpeedLimit($file_path, $kilobytes = 100) {
    if (file_exists($file_path)) {
    // 获取文件大小
    $file_size = filesize($file_path);

     // 设置下载响应头
     header('Content-Description: File Transfer');
     header('Content-Type: application/octet-stream');
     header('Content-Disposition: attachment; filename=' . basename($file_path));
     header('Content-Transfer-Encoding: binary');
     header('Expires: 0');
     header('Cache-Control: must-revalidate');
     header('Pragma: public');
     header('Content-Length: ' . $file_size);
    
     // 打开文件并进行读取
     $file = fopen($file_path, "rb");
    
     // 设置下载速度限制
     $limit_speed = $kilobytes * 1024; // 转换为字节
     $start_time = microtime(true);
     while (!feof($file)) {
         echo fread($file, $limit_speed);
         flush();
         usleep(1000000 / $limit_speed);
         $elapsed_time = microtime(true) - $start_time;
         if ($elapsed_time > 1) {
             $start_time = microtime(true);
         }
     }
    
     // 关闭文件句柄
     fclose($file);
     exit;
    

    } else {
    echo "文件不存在!";
    }
    }

// 调用方法,下载文件并限速
$file_path = "your_file_path"; // 替换为要下载的文件路径
downloadFileWithSpeedLimit($file_path, 100); // 设置下载速率为每秒 100KB

其他PHP实现文件下载限速的方法,需要的可以参考下