如何使用 php 检查文件夹中的某些文件扩展名

how to check for certain file extension in a folder with php

我有一个名为 uploads 的文件夹,里面有很多文件。我想看看里面有没有 .zip 文件。我如何用php检查里面是否有.zip文件?

使用glob()函数。

$result = glob("my/folder/uploads/*.zip");

它将 return 一个包含 *.zip 文件的数组。

这也有帮助,使用 scandir and pathinfo

 /**
 * 
 * @param string $directoryPath the directory to scan
 * @param string $extension the extintion e.g zip
 * @return []
 */
function getFilesByExtension($directoryPath, $extension)
{

    $filesRet = [];
    $files = scandir($directoryPath);
    if(!$files) return $filesRet;
    foreach ($files as $file) {
        if(pathinfo($file)['extension'] === $extension) 
            $filesRet[]= $file; 
    }

    return $filesRet;
}

可以像

一样使用
 var_dump(getFilesByExtension("uploads/","zip"));

@Bemhard 已经给出了答案,我正在添加更多信息以备将来使用:

如果您想在 uploads 文件夹中执行 运行 脚本,只需调用 glob('*.zip').

<?php
foreach(glob('*.zip') as $file){
    echo $file."<br/>";
}
?>

如果您有多个文件夹并且文件夹中包含多个 zip 文件,那么您只需要 运行 从根目录执行脚本。

<?php
$dir = __DIR__; // will get the exact path
$dirs = array_filter(glob('*'), 'is_dir'); // filter is directory or not.

$i = 1;
foreach ($dirs as $key => $value) {
    foreach(glob($value.'/*.zip') as $file){
        echo $file."<br/>"; // this will print all files inside the folders.
    }   
    $i++;
}
?>

额外的一点,如果你想删除所有带有这个 activity 的 zip 文件,你只需要 unlink 文件:

<?php
$dir = __DIR__; // will get the exact path
$dirs = array_filter(glob('*'), 'is_dir'); // filter is directory or not.

$i = 1;
foreach ($dirs as $key => $value) {
    foreach(glob($value.'/*.zip') as $file){
        echo $file."<br/>"; // this will print all files inside the folders.
        unlink($file); // this will remove all files.
    }   
    $i++;
}
?>

参考资料: Unlink Glob