Hakan Hakan - 4 months ago 9
PHP Question

Validate filename using PHP ("a-z", "0-9" and "-")

What is the best way to validate a filename using PHP and how can I do it?

I want to see if filename contains only "a-z", "0-9" and "-". Also make sure the filename has no capital letters.

$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. ';
}


I ended up doing something like this, to get rid of the file extension:

$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';
}

Answer
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. ';

}

Change ext with your required extension. Or better yet, strip it with pathinfo, and use finfo to ensure the file is of the correct type.