How to Create a Directory in PHP

09/05/2021

Contents

In this article, you will learn how to create a directory in PHP.

PHP mkdir() Function

In PHP, you can create a directory using the mkdir() function.

Here’s an example:

<?php
  $dir = "new_directory";

  if (!mkdir($dir, 0777, true)) {
    die('Failed to create directories...');
  }

  echo "Directory created successfully";
?>

In this example, mkdir creates a directory named “new_directory” with permission 0777. The third argument true specifies that intermediate directories should be created if they don’t exist.

Here are some additional details and best practices when using the mkdir() function in PHP:

  • Permissions: The second argument of the mkdir function specifies the permissions for the new directory. In the example, 0777 gives read, write, and execute permissions to the owner, group, and others. You can adjust these permissions as needed.
  • Error handling: The mkdir() function returns false if the directory creation fails, so it’s a good idea to include error handling in your code. In the example, the die statement is executed if mkdir() returns false, which displays an error message and stops the script.
  • Recursive directory creation: The third argument of mkdir() function specifies whether to create parent directories if they do not exist. Setting it to true enables recursive directory creation, and false (the default) disables it.
  • File system restrictions: Keep in mind that the mkdir() function may fail if the file system or server has restrictions on directory creation. For example, the user running the PHP script may not have sufficient permissions to create a directory in the specified location.

It’s important to validate the input and properly handle errors when using the mkdir() function to ensure that the function works as expected and to prevent security issues.