You need to enable JavaScript to run this app. PHP基于scandir的图片展示脚本如何排除目录内的PHP文件?
优惠活动
大模型
产品
解决方案
定价
更多

PHP基于scandir的图片展示脚本如何排除目录内的PHP文件?

问题根因

现有排除逻辑失效的核心是匹配规则设计错误:

  • 代码中使用的in_array($curimg, $ignore)是对完整文件名做精确全等匹配
  • 忽略数组中加入的".php",仅当目录内存在文件名恰好为.php的特殊空名文件时,才会被成功排除
  • 对于目录中实际存在的index.php、download.php这类带有效文件名的PHP脚本,其完整文件名和数组内的.php字符串并不相等,自然无法命中排除规则,会被正常遍历输出。
修正方案

方案1:最小改动,基于后缀的黑名单排除

仅需要把原来的“匹配完整文件名”逻辑,调整为“匹配文件后缀”,就能覆盖所有PHP类型的文件:

$images_dir = "/Images/";
$images = scandir($images_dir);
arsort($images);
// 需要精确跳过的系统固定项
$skip_exact = array(".", "..");
// 需要排除的文件后缀列表
$skip_ext = array("php", "phtml", "php3", "php4", "php5", "php7");
foreach($images as $curimg){
    // 跳过系统目录项
    if (in_array($curimg, $skip_exact)) continue;
    // 获取当前文件的小写后缀,兼容大小写后缀的情况
    $ext = strtolower(pathinfo($curimg, PATHINFO_EXTENSION));
    // 命中排除后缀直接跳过,不做输出
    if (in_array($ext, $skip_ext)) continue;
    // 修正原代码中路径拼接重复斜杠的问题
    echo "<a href=\"{$images_dir}{$curimg}\"><img src=\"{$images_dir}{$curimg}\" data-src=\"{$images_dir}{$curimg}\"></a>\n";
}

方案2:白名单过滤,适配图片展示脚本的核心场景

这个脚本的定位是展示文件夹内的图片,与其逐个排除所有非图片类型的文件,不如直接仅允许指定格式的图片进入输出流程,从根源上避免PHP脚本、文档、压缩包等非图片文件被误展示:

$images_dir = "/Images/";
$images = scandir($images_dir);
arsort($images);
// 仅放开允许展示的图片后缀
$allow_img_ext = array("jpg", "jpeg", "png", "gif", "webp", "bmp");
foreach($images as $curimg){
    if (in_array($curimg, array(".", ".."))) continue;
    $ext = strtolower(pathinfo($curimg, PATHINFO_EXTENSION));
    // 不属于允许的图片后缀,直接跳过
    if (!in_array($ext, $allow_img_ext)) continue;
    echo "<a href=\"{$images_dir}{$curimg}\"><img src=\"{$images_dir}{$curimg}\" data-src=\"{$images_dir}{$curimg}\"></a>\n";
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 21:45:07