使用PHP验证文件名("az","0-9"和" - ")

Hak*_*kan 6 php validation filenames file-upload

使用PHP验证文件名的最佳方法是什么?我该怎么做?

我想看看文件名是否只包含"az","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. ';
}
Run Code Online (Sandbox Code Playgroud)

我最终做了这样的事情,以摆脱文件扩展名:

$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';
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*son 9

if(preg_match('/^[a-z0-9-]+\.ext$/', $file)) {
    // .. upload
} else {
    echo 'The file "' . $file . '"was not uploaded. The file can only contain "a-z", "0-9" and "-". Allso the files must be lowercase. ';

}
Run Code Online (Sandbox Code Playgroud)

更改ext您所需的扩展名.或者更好的是,剥离它pathinfo,并使用finfo以确保文件的类型正确.