标签导航:
php 菜刀下载文件夹步骤:1. 获取文件夹内文件列表;2. 循环文件,判断是否为目录,若不是则获取文件大小、创建下载头、读取文件内容并输出。

php菜刀如何下载文件夹

如何使用 PHP 菜刀下载文件夹

步骤 1:获取文件列表

$dir = '/path/to/directory';
$files = scandir($dir);

步骤 2:循环文件并下载

foreach($files as $file) {
  if (is_dir($dir . '/' . $file)) {
    continue; // 跳过目录
  }

  // 获取文件大小
  $size = filesize($dir . '/' . $file);

  // 创建下载头
  header("Content-Type: application/octet-stream");
  header("Content-Disposition: attachment; filename=\"" . basename($file) . "\"");
  header("Content-Length: " . $size);

  // 读取文件内容并输出
  readfile($dir . '/' . $file);
}

示例代码:

<?php $dir = '/path/to/directory';
$files = scandir($dir);

foreach($files as $file) {
  if (is_dir($dir . '/' . $file)) {
    continue;
  }

  $size = filesize($dir . '/' . $file);

  header("Content-Type: application/octet-stream");
  header("Content-Disposition: attachment; filename=\"" . basename($file) . "\"");
  header("Content-Length: " . $size);

  readfile($dir . '/' . $file);
}

?>