Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

mkdir

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.

like image 485
lexa Avatar asked Nov 13 '13 21:11

lexa


1 Answers

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 :

  • https://www.drupal.org/files/1642532-drush-mkdir-race-condition.patch
  • https://github.com/KnpLabs/Gaufrette/blob/master/src/Gaufrette/Adapter/Local.php#L260
  • https://github.com/symfony/symfony/commit/04834521f1298c8fee2704b1c4b1df43b655eb60
like image 80
Ka. Avatar answered Sep 28 '22 00:09

Ka.