DT DT
DT DT

Reputation: 378

PHP is_dir() doesn't work when nested

Here is my folder structure:

main 
- folder_1
-- folder_1_1
-- folder_1_2
-- folder_1_3
- folder_2
-- folder_2_1
-- folder_2_2
-- folder_2_3

And here is my code:

<?php

$mainfolder ="main";

function readDirs($mainfolder){
    if(hasSubFolder($mainfolder)){
        echo("$mainfolder HAS sub folder");
    }else{  
        echo("$mainfolder DOESN'T HAVE sub folder");
    }   
}

function hasSubFolder($folder){ 
    $newPath="";
    if (is_dir($folder)) {  
        echo ("$folder IS a folder</br>"); 
        $handle = opendir($folder);
        while (false !== ($entry = readdir($handle))) {
            $newPath = $folder."\\".$entry;
            if (is_dir($newPath)){
                echo "$newPath IS a folder</br>";
            } else {                
                echo "$newPath IS NOT a folder</br>";
            }
        }       
    }   
}

readDirs($mainfolder);

?>

And this is what I get:

main IS a folder
main\. is NOT a folder
main\.. is NOT a folder
main\folder_1 is NOT a folder
main\folder_2 is NOT a folder
main DOESN'T HAVE sub folder

So I'd like to know why "if (is_dir($newPath))" doesn't return true even $newPath is a folder/dir. Is it because it's nested inside another another is_dir()?

Thank

Upvotes: 1

Views: 454

Answers (2)

Niels Keurentjes
Niels Keurentjes

Reputation: 41958

Since PHP can run on a multitude of platforms, which might use even more exotic directory separators than forward or backward slash, there's a beautiful system constant defined you can used instead: DIRECTORY_SEPARATOR.

It automatically contains the right separator for the current host OS, such as the backslash for Windows or the forward slash for a *nix system. You can then use:

$newPath = $folder.DIRECTORY_SEPARATOR.$entry;

This is always better than hardcoding it for any OS as the other answer suggests.

Currently, for backwards compatibility reasons, PHP internally always does a str_replace from / to DIRECTORY_SEPARATOR within its internal file functions, but this is not guaranteed to keep working forever - it costs performance and isn't strictly needed.

Upvotes: 5

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

Linux uses / for folder separation, and Windows does too. It's only DOS that doesn't. Replace \\ with / and you should be good to go.

Upvotes: 4

Related Questions