You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断ZipArchive中的压缩条目是文件夹还是文件?

问题:PHP ZipArchive如何判断条目是目录还是文件

🖥️ 代码示例

$zip = new ZipArchive;
$zip_path = './test.zip';

if($zip->open($zip_path))
{
  for($i = 0; $i < $zip->numFiles; $i++)
  {
    $file_path = $zip->getNameIndex($i);
    if(<MY ISSUE HERE>)
    {
      // 是目录
    }
    else
    {
      // 是文件
    }
  }
}

⛔ 问题描述

查阅了PHP官方ZipArchive文档,但无法确定$file_path(由$zip->getNameIndex($i)返回)对应的是目录还是文件。$zip->statIndex($i)的返回结果中也不包含该信息,示例返回如下:

Array
(
    [name] => foobar/baz
    [index] => 3
    [crc] => 499465816
    [size] => 27
    [mtime] => 1123164748
    [comp_size] => 24
    [comp_method] => 8
)

🎯 解决方案

方法1:检查路径末尾的斜杠

ZipArchive中目录的名称通常会以/结尾,直接通过字符串判断即可:

$zip = new ZipArchive;
$zip_path = './test.zip';

if($zip->open($zip_path))
{
  for($i = 0; $i < $zip->numFiles; $i++)
  {
    $file_path = $zip->getNameIndex($i);
    if(substr($file_path, -1) === '/')
    {
      // 是目录
      echo "目录:{$file_path}\n";
    }
    else
    {
      // 是文件
      echo "文件:{$file_path}\n";
    }
  }
}

方法2:通过external_attr属性判断

调用statIndex时传入ZipArchive::FL_UNCHANGED参数,获取完整的文件属性,然后通过位运算判断是否为目录:

$zip = new ZipArchive;
$zip_path = './test.zip';

if($zip->open($zip_path))
{
  for($i = 0; $i < $zip->numFiles; $i++)
  {
    $stat = $zip->statIndex($i, ZipArchive::FL_UNCHANGED);
    if (($stat['external_attr'] & 0x4000) === 0x4000) {
      // 是目录
      echo "目录:{$stat['name']}\n";
    } else {
      // 是文件
      echo "文件:{$stat['name']}\n";
    }
  }
}

0x4000是DOS文件属性中的目录标识位,通过与运算可以提取该属性,判断当前条目是否为目录。


内容的提问来源于stack exchange,提问作者4uruanna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 17:23:36