Check if string is valid filename

You may have a look in php's basename function, it will return with filename, see example below:

$file = '../../abc.txt';
echo basename($file); //output: abc.txt

Note: basename gets you the file name from path string irrespective of file physically exists or not. file_exists function can be used to verify that the file physically exists.


POSIX "Fully portable filenames" lists these: A-Z a-z 0-9 . _ -

Use this code to validate the filename against POSIX rules using regex:

  • / - forward slash (if you need to validate a path rather than a filename)
  • \w - equivalent of [0-9a-zA-Z_]
  • - . - dash dot space
$filename = '../../test.jpg';
if (preg_match('/^[\/\w\-. ]+$/', $filename)) 
    echo 'VALID FILENAME'; 
else 
    echo 'INVALID FILENAME';

If you want to ensure it has no path (no forwardslash) then change the regex to '/^[\w\-. ]+$/'.

Tags:

Php

Validation