Php dir function returns null even if there are files

I am using php's dir () function to get files from a directory and scroll through it.

$d = dir('path');

while($file = $d->read()) {
  /* code here */
}

      

But this returns false and gives

Calling member function read () on null

But this directory exists and the files are.

Also is there any alternative to my above code?

+3


source to share


4 answers


If you look at the documentation , you will see:

Returns a directory instance or NULL with incorrect parameters, or FALSE on another error.

So, Call to member function read() on null

means you got an error (I think it is failed to open dir: No such file or directory in...

).



You can use file_exists and is_dir to check if the given path is a directory and if it actually exists.

Example:

<?php
...
if (file_exists($path) && is_dir($path)) {
    $d = dir($path);

    while($file = $d->read()) {
      /* code here */
    }
}

      

0


source


try using this:

if ($handle = opendir('/path/to/files')) {
    echo "Directory handle: $handle\n";
    echo "Entries:\n";

    /* This is the correct way to loop over the directory. */
    while (false !== ($entry = readdir($handle))) {
        echo "$entry\n";
    }

    /* This is the WRONG way to loop over the directory. */
    while ($entry = readdir($handle)) {
        echo "$entry\n";
    }

    closedir($handle);
}

      



source: http://php.net/manual/en/function.readdir.php

+1


source


You can try this:

$dir = new DirectoryIterator(dirname('path'));
foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
        var_dump($fileinfo->getFilename());
    }
}

      

Source: PHP script to loop through all files in a directory?

+1


source


Check the file path if your path is correct. Then please try this code, it might help you. Thanks to

  <?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
  echo fgetc($myfile);
}
fclose($myfile);
?>

      

0


source







All Articles