How to Make a Directory in PHP

How to make a directory in php

Built into PHP is a handful of filesystem functions, all ready to use in your web application. Along with such how to use the basename PHP function, which removes the trailing name from provided path names, mkdir, another great PHP function that allows you to dynamically create system directories, without the need for the command line. But how do you use the mkdir function, and how do you ensure permissions on the folder are correct? We'll explore these questions and more, and give you insight into how to easily create file directories with PHP, along with easy-to-follow code examples.

What is the mkdir function?

Mkdir is a great function that everyone should get familiar with. It allows you to create a directory in your filesystem all with PHP. The mkdir function stands for, make directory. The great thing about this function is it does a lot more than just create the folder, it also handles permissions and recursive parent directories. The mkdir function is designed to create directories, not files. In order to create a new file, you could use something like PHP's touch function which would create a blank file. This function might be useful if for example, you had a folder on clients, and you wanted to have separate folders for each client to house their images. Then, each time a new client of yours uploaded an image, you could dynamically create a directory for them, using the mkdir function.

How does the PHP mkdir function work?

Let's explore how the mkdir function works, and how you can start creating dynamic directories on your server. The mkdir function allows for four parameters, the string directory name, integer permission value, boolean recursive flag, and context resource. In the first example, we can ignore all other parameters, apart from the name to create a test directory. This parameter is the only one that's required, otherwise, it will trigger a fatal error (ArgumentCountError in PHP 7.1+). Here, it's creating a new directory called test, in the same location as where the PHP script is run. If you want the directory to be created elsewhere, you must specify that.

# creates new dir called 'test'
mkdir('test');

By default, the folder 'test' will be created with PHP's default which is 0777. This permission value is intentionally open, meaning a greater amount of the system users will have access, including PHP, and you via FTP or SSH. The number refers to the octal value of the folder's permission groupings. The numbers relate to the different user groups and what level of access they have. The different permission levels range from read, write, and execute. This is a Unix-style permission system, managed by chmod, which you'll a lot. This permission system and the permission parameter will be completely ignored on Windows systems.

Next, we're creating the folder images, inside the parent folder static. As the third parameter in PHP mkdir function defaults to true, which is the recursive mode, it will also create the parent directories should they not exist. Make dir allows for both relative and absolute paths. Absolute paths tend to give you fewer problems when moving code around, compare to a relative path. We can use one of PHP's magic constants "__DIR__" to pass the full system path to PHP, which is also better practice, and allows us to move files around without breaking file links.

# creates a new dir called 'images' in a different location
mkdir('static/images');

# providing the full system path is good practice
mkdir(__DIR__ . '/static/images');

If you want to adjust the default permission value you can by setting the second parameter in the mkdir function. When setting the permission value, it is best practice to specify the int as an octal number. This means it should always have a leading zero. In the following example, we've adjusted the default permission of 0777 to 0775, which means we've removed the 'write' permission from the public group. For each group, you take all the permissions and add them up to give you your octal number.

  • Use 1 for execute permissions
  • Use 2 for write permissions
  • Use 4 for read permissions

Based on each group, add together each one's permissions. For example, if we wanted the owner's permissions to have all three permissions, the octal value would be 7 because 1 (execute) + 2 (write) + 4 (read) = 7. In the following example, we've given the owner and the group full permissions, which is 077, and the public group only read and execute, which is 5. Resulting in, 0775. Again, it's 5 because we've added the following permissions together, 1 (execute) + 4 (read) = 5.

# Here we are creating a directory called test, but slightly more protected
mkdir('test', 0775);

There might be times when we don't want to recursively create the parent directories. That might be because the parents might require different permissions, different from the one that you're trying to create. By default, if the parent's directories don't exist, they get created, but with the same permission.

# creates a new dir called 'images' but not recursively
mkdir('static/images', 0777, false);

Finally, we can also pass a context stream resource to the mkdir function, which allows you to control the file stream. You'll in most cases won't need to use this and the default will suffice.

Possible errors or exceptions when using mkdir

The mkdir function does a great job of creating directories for us. There are some things to look out for when working with it in PHP. Mkdir will return a boolean value when used. That will be either true (success), or false (failed).

# outputs true
var_dump(mkdir('test'));

However, the function will produce PHP warnings if, the directory already exists, or the function is prevented from creating a new directory because of the given permissions. Because of this will have to make sure that the directory isn't already set in the file system. To do that we can use the is_dir or file_exists functions in PHP. Either one can be used to check if a given directory exists before attempting to create it with mkdir. Again, it doesn't matter which function you use to check the folder, but there is a general sway towards the is_dir function as the naming of this and the mkdir function are clearer to other developers in terms of what's going on.

# outputs true
var_dump(mkdir('test'));

# this will now fail and produce a E_WARNING.
var_dump(mkdir('test'));

Checking if a directory already exists is straightforward. To avoid triggering a PHP warning, wrap your mkdir function in an if statement, of which you pass the same folder string name to is_dir (or file_exists).

$dirName = 'test';

if (!is_dir($dirName)) {
 mkdir('test');
}

Conclusion

Mkdir is an easy way to create directories in PHP, with the extra ability to set permission levels on Unix-based systems.

  • Always provide the directory name as a string
  • Always check if the directory is already in place, before attempting to call the mkdir function
  • Permissions in Windows systems are ignored
  • The directory path could be a URL instead if fopen wrappers are enabled (if necessary permissions and conditions are met)

Be sure to check out more of our great PHP guides and tutorials, all with the aim of helping make you a better PHP programmer.

Senior PHP developer. Author of Dev Lateral guides and tools. The complete place for PHP programmers. Available to hire to help you build or maintain your PHP application.

Looking for industry-leading PHP web development?

API development WordPress Hosting ★ and more 🐘

We use cookies to enhance your browsing experience, and analyse website traffic in accordance with our Privacy and Cookie Policy. Our cookies, including those provided by third parties, collect anonymous information about website usage and may be used for targeted advertising purposes. By clicking "Reject non-essential" you can opt out of non-essential cookies. By clicking "Accept all" you agree to the use of all cookies.


Reject non-essential Accept all