Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check a string for a valid directory name

Tags:

directory

php

I need a function, native or user made, that checks if a string is a valid directory name. I've had a look through the PHP documentation and I can only find the function is_dir which checks if it's an existing directory or not and not a valid name for a directory.

like image 453
Jack B Avatar asked Oct 01 '12 19:10

Jack B


2 Answers

This should work for you.

See regex for validating folder name & file name

if (strpbrk($filename, "\\/?%*:|\"<>") === FALSE) {
  /* $filename is legal; doesn't contain illegal character. */
}
else {
  /* $filename contains at least one illegal character. */
}
like image 50
Gregory Burns Avatar answered Oct 13 '22 00:10

Gregory Burns


This would work. You can modify the second and third arguments to your needs.

if (!mkdir($directory, 0700, true)) {
    die('Error: Illegal directory.');
}

Note that this will create the directory if the directory name is valid. However, in my humble opinion (and without knowing your particular use case), this is the preferred way in most languages to handle checking directory name validity. Just attempt create the directory, and if it fails, then tell them that it failed.

The benefits of this is that it keeps your code file system agnostic and it is the least error-prone method to validate and create a directory, since no other process or thread will be able to create a directory between when you validate the directory and when you create it.

The drawback is that this method assumes you want to create the directory immediately.

Of course, there are multiple reasons that mkdir() could fail (e.g., insufficient permissions, hardware failure, invalid directory name, etc.), so you may want to display different error messages to the user based on the error. Unfortunately, PHP does not have quite as robust exception handling as some other languages do, but should you want to go down this road, you should be able to use an approach such as in this answer to catch the different warnings that mkdir() can generate.

like image 23
Stephen Booher Avatar answered Oct 13 '22 00:10

Stephen Booher