Home > OS >  PHP is_dir yields different results depending on where it's run from?
PHP is_dir yields different results depending on where it's run from?

Time:07-22

I'm trying to make a website using php, where the folder structure looks like this:

[root]
├ index.php
├ css.css
├ directory1
│ └ index.php
├ directory2
│ └ index.php
├ directory3
│ └ index.php
├ img
└ imports
  ├ footer.php
  ├ head.php
  └ header.php

Inside imports/header.php I have the following code to generate the header's redirect buttons

<?php 
    $dirs = scandir($_SERVER["DOCUMENT_ROOT"]);
    print_r($dirs);
    $dirs = array_filter($dirs, 'is_dir');
    print_r($dirs);
    $dirs = array_diff($dirs,['img','imports','.','..']);
    print_r($dirs);
    foreach ($dirs as $dir) {
        echo('<a href="/'.$dir.'">
        <p>
        '.ucwords(str_replace('-',' ',$dir)).'
        </p></a>');
    }
?>

For some reason that I can't understand though, when running the script in /index.php, using include $_SERVER["DOCUMENT_ROOT"].'/imports/header.php';, I get the following output from the sequence of print_r():

Array ( [0] => . [1] => .. [2] => css.css [3] => directory1 [4] => img [5] => imports [6] => index.php [7] => directory2 [8] => directory3 )
Array ( [0] => . [1] => .. [3] => directory1  [4] => img [5] => imports [7] => directory2 [8] => directory3 )
Array ( [3] => directory1   [7] => directory2 [8] => directory3 )

Which matches my expectations. HOWEVER, in /directory1/index.php, having also used include $_SERVER["DOCUMENT_ROOT"].'/imports/header.php'; to import the script, it outputs the following:

Array ( [0] => . [1] => .. [2] => css.css [3] => directory1 [4] => img [5] => imports [6] => index.php [7] => directory2 [8] => directory3 )
Array ( [0] => . [1] => .. )
Array ( ) 

So it gets the same directory to scan, scans it, gets the same files and folders, yet only recognizes the . and .. as directories the second time around. I suspect it has something to do with the is_dir() function that is being run, but I have no clue why it has this different behavior. Could anyone help me?

CodePudding user response:

is_dir() doesn't know that the filenames came from the document root, it's looking for them in the current directory. Use a filter function that concatenates them to the directory.

$dirs = array_filter($dirs, function($dir) {
    return is_dir($_SERVER['DOCUMENT_ROOT'] . '/' . $dir);
});
  •  Tags:  
  • php
  • Related