Search code examples
phpif-statementwhile-loopxampplocalhost

Is this the correct way to hide a file or folder in PHP


I am just learning more about using classes in PHP. I know the code below is crap has I need help. Can someone just let me know if I am going in the right direction?

while($entryName=readdir($myDirectory)) {
    $type = array("index.php", "style.css", "sorttable.js", "host-img");
    if($entryName != $type[0]){
        if($entryName != $type[1]){
            if($entryName != $type[2]){
                if($entryName != $type[3]){
                    $dirArray[]=$entryName;
                }
            }
        }
    }
}

Solution

  • What you seem to want is a list of all the files in your directory that do not have one of four specific names.

    The code that most resembles yours that would do it more efficiently is

    $exclude = array("index.php", "style.css", "sorttable.js", "host-img");
    $dirArray = [];
    
    while ($entryName = readdir($myDirectory)) {
        if (!in_array($entryName, $exclude)) {
            $dirArray[] = $entryName;
        }
    }
    

    Alternately, you can dispense with the loop (as written, will include both files and directories in the directory you supply)

    $exclude = array("index.php", "style.css", "sorttable.js", "host-img");
    $contents = scandir($myDirectory);
    $dirArray = array_diff($contents, $exclude);
    

    Edit to add for posterity:

    @arkascha had an answer that used array_filter, and while that example was just an implementation of array_diff, the motivation for that pattern is a good one: There may be times when you want to exclude more than just a simple list. It is entirely reasonable, for instance, to imagine you want to exclude specific files and all directories. So you have to filter directories from your list. And just for fun, let's also not return any file whose name begins with ..

    $exclude = ["index.php", "style.css", "sorttable.js", "host-img"];
    $contents = scandir($myDirectory); // myDirectory is a valid path to the directory
    
    $dirArray = array_filter($contents, function($fileName) use ($myDirectory, $exclude) {
        if (!in_array($fileName, $exclude) && strpos('.', $fileName) !== 0) {
            return !is_dir($myDirectory.$fileName));
        } else {
            return false;
        }
    }