lexa
lexa

Reputation: 1065

mkdir function throw exception 'File exists' even after checking that directory doesn't exist

I stumbled upon a every strange behaviour with mkdir function in PHP. Below is an example of my simple code.

$filepath = '/media/static/css/common.css';
if (!file_exists(dirname($filepath)))
{
   mkdir(dirname($filepath), 0777, TRUE);
}

'media' folder always exists. All folders into the 'media' folder have to be created. Before coping the common.css file I'd like to create a folder '/static/css'.

mkdir OCCASIONALLY throw exception "File exists". I tried to create a folder if it doesn't exist. 'File exists' is a common error, I assume, so the folder exists.

I understand that there is a very little info I gave you and it is really strange error. Maybe you can give me any advice what I have to do and how I can test that bug and find the bottleneck.

Server: CentOS release 6.4

Thank you.

Upvotes: 6

Views: 6084

Answers (1)

Ka.
Ka.

Reputation: 1209

This is a race condition situation. You should do something like that :

$filepath = '/media/static/css/common.css';
// is_dir is more appropriate than file_exists here
if (!is_dir(dirname($filepath))) {
    if (true !== @mkdir(dirname($filepath), 0777, TRUE)) {
        if (is_dir(dirname($filepath))) {
            // The directory was created by a concurrent process, so do nothing, keep calm and carry on
        } else {
            // There is another problem, we manage it (you could manage it with exceptions as well)
            $error = error_get_last();
            trigger_error($error['message'], E_USER_WARNING);
        }
    }
}

ref :

Upvotes: 10

Related Questions