简体   繁体   中英

Check a string for a valid directory name

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.

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. */
}

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 (eg, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM