PHP check if a filename is valid

Sometimes we need to check if a filename contains special character etc. One possible approach is to check for alphanumeric characters and few more characters like dot and dash. Here is code snippet and outcome to check valid filename with this approach and using preg_match.

function is_valid_name($file) {
  return preg_match('/^([-\.\w]+)$/', $file) > 0;
foreach (array("foo_bar.php", "file with space.txt", "~tilde.txt") as $file) {
  echo "Is name [$file] valid: ";
  var_dump(is_valid_name($file)) ;
Is name [foo_bar.php] valid: bool(true)
Is name [file with space.txt] valid: bool(false)
Is name [~tilde.txt] valid: bool(false)
Env: PHP 5.5.9 (Linux)

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments