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.
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 :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With