wellmannered
wellmannered

Reputation: 69

PHP and Creating Directories

Quick question. I'll start off with an example.

I have a social site similar to Facebook. When a user signs up my PHP script creates a directory named after his username and a custom sub-directory for this user called "photos".

The "photos" directory is never created when someone signs up. I assume it is because the actual server hasn't created the actual username directory in the first place.

My solution is that anytime i need to execute the photo function on my site for a user I should check if the folder exists and if not create it, which works fine. Is this standard procedure? Or is there a better way to create multiple directories at the same time while running checks.

When someone signs up I run this code, and the latter if statement doesn't successfully create the photos folder, so i check these two statements anytime I am editing something that would go in photos as a check for if the folder exists.

if (!file_exists("user/$username")) {
    mkdir("user/$username", 0755);
}
if (!file_exists("user/$username/photos"))
{
    mkdir("user/$username/photos", 0755);
}

Upvotes: 0

Views: 120

Answers (2)

Raja Khoury
Raja Khoury

Reputation: 3195

You can do a quick directory 'exists' check like this

   function check($images_dir) {
        if($handle = opendir($images_dir)) {
            // directory exists do your thing

               closedir($handle);
            } else {
             // create directory
           }                
        }

Where $images_dir = path/directory/user/$username

Upvotes: 0

sitilge
sitilge

Reputation: 3737

The directories are created sequentially/synchronously thus once execution of the first mkdir() is finished the folder should be there with the indicated permission set.

As stated here the mkdir()

Returns TRUE on success or FALSE on failure.

and

Emits an E_WARNING level error if the directory already exists.

Emits an E_WARNING level error if the relevant permissions prevent creating the directory.

So you can go:

if (!file_exists("user/$username")) {
    if(mkdir("user/$username", 0755))
    {
        //directory created
        if (!file_exists("user/$u/photos"))
        {
            mkdir("user/$username/photos", 0755);
        }
    }
    else
    {
        //directory not created
    }
}

If the mkdir() returns false - check the logs or handle the error.

Upvotes: 1

Related Questions