获取没有目录的PHP文件夹列表



设置URL参数时,如果有此parametername/foldername的文件夹,则应搜索。但是Glob功能为我提供了目录和折叠式名称。我如何在没有目录的情况下列出foldername?

<?php
if(isset($_GET["customer"])){
    $customer = $_GET['customer'];
    $path = 'cover/';
    $dirs = glob($path.'*', GLOB_ONLYDIR);
    print_r($dirs);
    if(array_search($customer, $dirs) !== false) {
        echo "found something";
    }
    else {
        echo "nothing found";
    }
}
else {
    echo "no parameter in the url";
}
?>

此代码的结果:

Array ( [0] => cover/twDE [1] => cover/twEN )

所以我想在没有封面的foldernames中拥有一个数组/...

谢谢您的帮助格雷格

尝试以下:

function customResult($dirsFound) {
    return str_replace('cover/', '', $dirsFound);
}
$customer = isset($_GET['customer']) ? $_GET['customer'] : '';
if (strlen($customer)) {
    $path = 'cover/';
    $dirs = array_map('customResult', glob($path . '*', GLOB_ONLYDIR));
    if (array_search($customer, $dirs) !== false) {
        echo "found something";
    } else {
        echo "nothing found";
    }
} else {
    echo "no parameter in the url";
}
$dirs = glob($path.'*', GLOB_ONLYDIR); // get all folders/directories
// loop in folders array
foreach ($dirs as $key => $val) {
    // cut "cover/" string from paths
    $dirs[$key] = str_replace("cover/", "", $val);
}
// check is folder with name "folderName" exists in array
if (in_array("folderName", $dirs)) {
    echo "Exists";
}

几种方法。

使用chdirscandir

chdir('./cover');
$dirs = array_filter(scandir('.'), 'is_dir'));

使用FilesystemIterator

$fsi = new FileSystemIterator('./cover');
foreach ($fsi as $element) {
    if ($element->isDir()) {
        echo $element->getbasename(), PHP_EOL;
    }
}

或使用globbasename

print_r(array_map('basename', glob('./cover', GLOB_ONLYDIR)));

以上所有内容都将为您提供"封面"文件夹中的目录名称。然后,您可以运行array_search或其他任何内容。

但是:由于您的文件夹名称似乎与您的客户名称相对应,因此您也可以直接 glob,例如。

glob("./cover/$customer", GLOB_ONLYDIR);

这将为您节省in_array的其他呼叫。如果结果是一个空数组,则没有客户目录。

话虽如此,如果您只验证路径 客户值是否为目录,例如。

if (is_dir("./cover/$customer")) {
    // found your customer's folder
}

在旁注:如果使用此方法,则应确保$customer变量不包含允许目录遍历的字符,以防止恶意用户尝试映射您的文件系统布局。

最新更新