-2

I am trying to include .php files from a directory with this type of code. But its not working. Can anyone help me? Thank you.

<?php
$dir = "/file/";
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while(($file = readdir($dh)) !== false) {
            if ($file != "." && $file != "..") {
               include "$file";
            }
        }
        closedir($dh);
    }
}
?>
  • Why don't use [autoload](https://www.php.net/manual/en/language.oop5.autoload.php)? – Simone Rossaini Jan 13 '21 at 14:48
  • 2
    What do you mean by "not working"? What **exactly** is not working? What have you tried to debug the problem? – Nico Haase Jan 13 '21 at 14:50
  • When you say its not working, what do you mean? It's hard to debug from here. One thing that would be worth checking is that with `/file/`, a slash at the start usually means it will search from the root of your server. You may want to try using something like `./file/` – Djave Jan 13 '21 at 14:51
  • `$file` contains just the file name, so you will have to prefix that with `$dir`, so that it will find the file in that subfolder from the current location. (Assuming “normal” `include_path` configuration settings.) – CBroe Jan 13 '21 at 14:51
  • Try using [PHP Glob](https://www.php.net/manual/en/function.glob.php). And [Reading this Question](https://stackoverflow.com/questions/12109042/php-get-file-listing-including-sub-directories) – Martin Jan 13 '21 at 14:59
  • @NicoHaase I have did `echo` in loop where result was correctly working. but in loop when i tried to loop over **files name** with `include`, its result was infinity looping. is there another way to `include` all files from a folder?? – Robin Ringku Jan 13 '21 at 15:19
  • And what have you tried to debug **why** that infinite loop occurs? Are you probably including the file that runs this algorithm itself, such that it includes itself recursively? – Nico Haase Jan 13 '21 at 15:41
  • @CBroe Thank You. Its worked correctly after using `$dir` as prifix. – Robin Ringku Jan 14 '21 at 15:23

1 Answers1

0

Its worked correctly after using $dir as prifix of $file.

<?php
$dir = "../file/";
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            if ($file != "." && $file != "..") {
                include_once $dir . $file;
            }
        }
        closedir($dh);
    }
}
echo $a . "<br>" . $b;

?>