检查php中是否存在正则表达式文件


check file exist with regular expression in php

我在服务器上上传了客户id的图像。但我不想上传文件的多种格式两次(例如,应该只有一个图像为客户id=1,是1.jpg或1.png)

我如何在更新图像时全局检查该文件是否已经存在?

我可以检查文件是否存在而没有文件扩展名吗?

我正在使用这个命令来检查文件。

file_exists('./media/customer-id/'.$cus_id);

使用scandir()运行类似ls的命令并接收目录内容数组。然后循环遍历这些文件,看看是否有与客户ID匹配的文件。

$exists = false;
foreach(scandir('./media/customer-id') as $file) {
    if(preg_match('/^' . $customer_id . ''.$/', $file)) {
        $exists = true;
        break;
    }
}

您可以使用glob()进行此操作并计算结果。

function patternExists($pattern) {
    return count(glob($pattern)) > 0;
}

并像这样使用

if (patternExists("./media/customer-id/".$cus_id."*")) {
    // bad!
}