Question

I want to create a new folder if there isn't already one created. In order to do that I wrote:

//Set up the log directory

if(is_dir(dirname(LOG_PATH))) {

} else {
    mkdir(LOG_PATH, 0777, true);
    echo "Directory created. ". LOG_PATH ."<br />";
}

LOG_PATH = E:\xampp\htdocs\photo\logs\

There is a photo folder, but there is no logs folder (I want to create that folder).

Am I missing something, because the if statement here is true. It shouldn't be.

Was it helpful?

Solution

dirname(LOG_PATH) returns the parent of the LOG_PATH (E:\xampp\htdocs\photo), so your if statement is true when the photo folder exists, not when the logs folder exists.

You should modify the condition to be:

if (is_dir(LOG_PATH)) {

} else {
    mkdir(LOG_PATH, 0777, true);
    echo "Directory created. ". LOG_PATH ."<br />";
}

And, if you are leaving the first branch empty, just negate the condition:

if (!is_dir(LOG_PATH)) {
    mkdir(LOG_PATH, 0777, true);
    echo "Directory created. ". LOG_PATH ."<br />";
}

And by the way, the mkdir call may fail if you don't have permissions to create a new folder there, so you should check if that fails or not:

if (!is_dir(LOG_PATH)) {
    if (mkdir(LOG_PATH, 0777, true)) {
        echo "Directory created. ". LOG_PATH ."<br />";
    } else {
        throw new Exception("Can't create folder " . LOG_PATH);
    }
}

OTHER TIPS

The 'mkdir' function doesn't function correctly on Windows when the path contains forward slashes. The part of the path with the forward slashes doesn't get created.

mkdir('c:/a/b/c/d', 0775, true);

You get the error message: Warning: mkdir() [function.mkdir]: No such file or directory

Please use backslashes under Windows or use the constant DIRECTORY_SEPARATOR.

mkdir('c:\a\b\c\d', 0775, true); mkdir('c:'.DIRECTORY_SEPARATOR.'a'. DIRECTORY_SEPARATOR.'b'. DIRECTORY_SEPARATOR.'c'. DIRECTORY_SEPARATOR.'d', 0775, true);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top