什么是使用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
消息有误导性,因为它似乎是指文件内容而不是名称。 - Grant Thomas