Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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';
}
like image 790
Hakan Avatar asked Dec 14 '11 08:12

Hakan


2 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.

like image 55
Michael Robinson Avatar answered Nov 15 '22 19:11

Michael Robinson


if(preg_match('/^[a-z0-9-]+$/',$file)) {
   // $file is valid
} else {
   // $file is not valid
}
like image 2
codaddict Avatar answered Nov 15 '22 20:11

codaddict