PASSWORD RESET

Your destination for complete Tech news

PHP

How to create a folder if it doesn’t exist in PHP?

362 0
< 1 min read

To create a folder in PHP if it doesn’t exist, you can use the mkdir function. This function creates a new directory with the specified permissions.

Here’s an example of how you can use it:

$folder = '/path/to/folder';
if (!file_exists($folder)) {
    mkdir($folder, 0755, true);
}

In this example, the file_exists function is used to check if the folder already exists. If it does not exist, the mkdir function is called to create it. The 0755 argument specifies the permissions for the new folder (read and execute for owner, read for others), and the true argument indicates that the function should create missing directories in the path (if any).

Note that the mkdir function returns a boolean value indicating whether the directory was successfully created or not. You can use this value to check if the operation was successful or not.

if (mkdir($folder, 0755, true)) {
    // Folder was created successfully
} else {
    // Folder could not be created
}

You can also use the is_dir function to check if a path is a directory, and the is_writable function to check if a directory is writable.

if (!is_dir($folder)) {
    // Folder does not exist
}

if (is_writable($folder)) {
    // Folder is writable
} else {
    // Folder is not writable
}

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.