【发布时间】:2023-04-08 15:15:02
【问题描述】:
使用 PHP 验证文件名的最佳方法是什么?我该怎么做?
我想看看文件名是否只包含“a-z”、“0-9”和“-”。还要确保文件名没有大写字母。
$file = 'the-name.ext';
if ($file == 'only contains a-z, 0-9 or "-"' // HOW TO
&& $file == 'lowercasse' // HOW TO
&& $file == 'a-z') // HOW TO
{
// upload code here
}
else{
echo 'The file "' . $file . '"was not uploaded. The file can only contain "a-z", "0-9" and "-". Allso the files must be lowercasse. ';
}
我最终做了这样的事情,以摆脱文件扩展名:
$filename = 'fil-name.jpg';
$filname_without_ext = pathinfo($filename, PATHINFO_FILENAME);
if(preg_match('/^[a-z0-9-]+$/',$filname_without_ext)) {
echo'$file is valid';
} else {
echo'$file is not valid';
}
【问题讨论】:
-
另一方面:您的
else消息具有误导性,因为它似乎指的是文件内容,而不是名称。
标签: php file-upload filenames validation