w3resource

PHP function to check directory and create If not found


13. Check/Create Directory if Not Exists

Write a PHP function to check if a directory exists and create it if it doesn't.

Sample Solution:

PHP Code :

<?php
function checkAndCreateDirectory($directory) {
    try {
        if (!is_dir($directory)) {
            if (!mkdir($directory, 0777, true))
            {
                throw new Exception("Error creating the directory.");
            }

            echo "
Directory created successfully."; } else { echo "
Directory already exists."; } } catch (Exception $e) { echo "An error occurred: " . $e->getMessage(); } } // Usage: $directory = "i:/data1"; checkAndCreateDirectory($directory); $directory = "i:/data2"; checkAndCreateDirectory($directory); ?>

Sample Output:

Directory already exists.
Directory created successfully.

Explanation:

In the above exercise -

First, we define a function called checkAndCreateDirectory() that takes a directory path as input.

Inside the function, we use is_dir() to check if the directory already exists. If it doesn't exist, we use mkdir() to create the directory with 0777 permissions. The third argument "true" ensures that any necessary parent directories are also created. If creation succeeds, we display a success message. If there is an error creating the directory, we throw an exception with the error message "Error creating the directory."

If the directory already exists, we display the message "Directory already exists."

Flowchart:

Flowchart: PHP function to check directory and create If not found

For more Practice: Solve these Related Problems:

  • Write a PHP script to check if multiple directories exist and create any that are missing, reporting the results.
  • Write a PHP function to recursively create a nested directory structure if it does not exist.
  • Write a PHP program to validate a directory path and generate it with proper permissions if not found.
  • Write a PHP script to check for a directory's existence, create it if necessary, and then write a file to that directory.

PHP Code Editor:



Contribute your code and comments through Disqus.

Previous: Display messages for different file types.
Next: Locate and display line numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.