PHP实现文件下载限速功能的方法详解

限速下载文件的原理是通过控制数据传输的速率来限制下载的速度。在PHP中,我们可以通过以下步骤来实现限速下载文件的功能:

设置下载响应头: 在发送文件内容之前,设置正确的HTTP响应头,包括Content-Type、Content-Disposition等,以便浏览器能够正确处理文件下载。

打开文件并读取内容: 使用PHP的文件操作函数,打开要下载的文件并读取其中的内容。在读取文件内容时,我们需要进行限速处理,确保下载速率不超过预设的限制。

控制下载速率: 在循环读取文件内容的过程中,通过控制每次读取的数据量和每次读取的时间间隔来实现限速。通常是通过 usleep() 函数来实现暂停一段时间。

输出文件内容: 将读取的文件内容输出到浏览器,实现文件的下载。通过循环读取文件内容并输出,直到文件的所有内容都被发送给浏览器。

关闭文件句柄: 在下载完成后,关闭文件句柄,释放资源。

/**
 * 下载文件并限速
 *
 * @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实现文件下载限速的方法,需要的可以参考下

大文件限速下载

<?php
//设置文件最长执行时间
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);
  // 打开文件
  $fp = fopen($file, \'rb\');
  // 设置指针位置
  fseek($fp, 0);
  // 开启缓冲区
  ob_start();
  // 分段读取文件
  while (!feof($fp)) {
    $chunk_size = 1024 * 1024 * 2; // 2MB
    echo fread($fp, $chunk_size);
    ob_flush(); // 刷新PHP缓冲区到Web服务器    flush(); // 刷新Web服务器缓冲区到浏览器
    sleep(1); // 每1秒 下载 2 MB
  }
  // 关闭缓冲区
  ob_end_clean();
  fclose($fp);
} else {
  echo \'file not exists or has been removed!\';
}
exit();

php控制文件下载速度的方法

<?php
 /*
 * set here a limit of downloading rate (e.g. 10.20 Kb/s)
 */
 $download_rate = 10.20;
 $download_file = \'download-file.zip\';
 $target_file = \'target-file.zip\';
 if(file_exists($download_file)){
  /* headers */
  header(\'Last-Modified:\'.gmdate(\'D, d M Y H:i:s\').\'GMT\');
  header(\'Cache-control: private\');
  header(\'Content-Type: application/octet-stream\');
  header(\'Content-Length: \'.filesize($download_file));
  header(\'Content-Disposition: filename=\'.$target_file);
  /* flush content */
  flush();
  /* open file */
  $fh = @fopen($download_file, \'r\');
  while(!feof($fh)){
   /* send only current part of the file to browser */
   print fread($fh, round($download_rate * 1024));
   /* flush the content to the browser */
   flush();
   /* sleep for 1 sec */
   sleep(1);
  }
  /* close file */
  @fclose($fh);
 }else{
  die(\'Fatal error: the \'.$download_file.\' file does not exist!\');
 }
?>

php限制下载速度

// local file that should be send to the client
$local_file = \'test-file.zip\';
// filename that the user gets as default
$download_file = \'your-download-name.zip\';
// set the download rate limit (=> 20,5 kb/s)
$download_rate = 20.5;
if(file_exists($local_file) && is_file($local_file)) {
 // send headers
 header(\'Cache-control: private\');
 header(\'Content-Type: application/octet-stream\');
 header(\'Content-Length: \'.filesize($local_file));
 header(\'Content-Disposition: filename=\'.$download_file);
 // flush content
 flush();
 // open file stream
 $file = fopen($local_file, \"r\");
 while (!feof($file)) {
 // send the current file part to the browser
 print fread($file, round($download_rate * 1024));
 // flush the content to the browser
 flush();
 // sleep one second
 sleep(1);
 }
 // close file stream
 fclose($file);
}
else {
 die(\'Error: The file \'.$local_file.\' does not exist!\');
}

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容