Home » Php » file upload – Validate filename using PHP ("a-z", "0-9" and "-")

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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';
}
How to&Answers:
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.

Answer:

if(preg_match('/^[a-z0-9-]+$/',$file)) {
   // $file is valid
} else {
   // $file is not valid
}

Answer:

Simply using regex will do the work for you

([a-z0-9-]+)

This pattern will match a-z, 0-9 and –