Search code examples
phppathincluderelative-path

Scandir relative to the path of file when included?


I have the following code in a file which is included into a host of other pages which require this information.

$directory_list = scandir("../packages");
$known_directories = [
  ".",
  ".."
];
$unknown_directories = $result = array_diff($directory_list, $known_directories);

It works perfectly when I open the file that contains this code directly. However, this file needs to be able to provide this information to other files by being included in said files. It seems that scandir is operating on a path relative to the file that INCLUDED this code.

How would I use the included file's path regardless of where this file is included?


Solution

  • Try to add dirname(__FILE__) to your path into scandir:

    $directory_list = scandir(dirname(__FILE__)."/../packages");
    $known_directories = [
      ".",
      ".."
    ];
    $unknown_directories = $result = array_diff($directory_list, $known_directories);
    

    It should work because __FILE__ is described here

    __FILE__ The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.

    You even can replace dirname(__FILE__) with __DIR__

    __DIR__ The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.