Search code examples
phpmkdirfile-exists

Why does PHP think this folder doesn't exist?


I'm having trouble creating a folder and writing into it.

if(file_exists("helloFolder") || is_dir("helloFolder")){
    echo "folder already exists";
} else {
    echo "no folder, creating";
    mkdir("helloFolder", 0755);
}

This returns "no folder, creating" even when the folder already exists. Then I get this error:

Warning:  mkdir() [function.mkdir]: No such file or directory in script.php on line 18

Warning: file_put_contents(/filename.txt) [function.file-put-contents]: failed to open stream: Permission denied in script.php on line 58

What is very strange is that I call three separate scripts that do this, and while the one always works, the other two always give this error. I'm calling the scripts synchronously, so I don't think there's any overlapping going on. Everything else is the same between them. All have permissions 644, all folders have permission 755.


Solution

  • First of all, you should adhere to the absolute patches when working with FileSystem, and also there are two minor flaws:

    • is_dir() - Checks whether file exists and its a directory. Therefore file_exists() is kinda redundant.

    • If you work with the same string anywhere else, it would be better to save its value in a variable.

    And finally, your code should look like this,

    $target = dirname(__FILE__) . '/hellodir';
    
    if (is_dir($target)) {
    
        echo "folder already exists";
    
    } else {
    
        echo "no folder, creating";
        // The 3-rd bool param includes recursion
        mkdir($target, 0777, true);
    }
    

    This will work as expected.