W3docs

php · PHP basics

Which function in PHP can be used to create a new directory?

Answers

  • mkdir()
  • create_dir()
  • new_directory()
  • dir_create()
# Understanding the mkdir() Function in PHP The `mkdir()` function in PHP enables the creation of a new directory. This in-built utility command stands for "make directory", and it's also used in the shell command line environment of UNIX-based systems. The `mkdir()` function is widely used in PHP scripting when there is a need to create a new directory. ## PHP mkdir() Function Syntax Here is the basic syntax for the `mkdir()` function in PHP: ```php mkdir(directory,mode,recursive,context) ``` In this syntax: - `directory`: Defines the name of the directory to be created. - `mode`: It's optional, specifying the permissions for the directory. Default is `0777`, which means the widest possible access. - `recursive`: An optional parameter, if set to TRUE, allows the creation of nested directories specified in the `directory` parameter. - `context`: This is also optional, specifying a set of parameters and options that can modify the behavior of a stream. ## Basic Example of mkdir() in PHP Here's a simple example of how you can use the `mkdir()` function in PHP: ```php ``` In this code snippet, a new directory named "new_directory" is being created. If the directory creation fails for any reason (like insufficient permissions), the script will halt execution and display the message - 'Failed to create new directory...'. ## Best Practices 1. Always check if a directory already exists before trying to create it. You can use the `is_dir()` function in PHP to perform this check. 2. Be careful while setting the `mode` parameter. Giving full permission (0777) could pose security risks, particularly in a shared hosting environment. 3. Error handling: Always add error handling code when using `mkdir()` function to handle cases when the directory could not be created. In conclusion, the `mkdir()` function is an effective PHP function for directory creation. However, it's important to use it wisely and securely, considering potential file permissions and ensuring proper error handling.