3

I'm using php dir() function to get files from directory and loop through it.

$d = dir('path');

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

But this returns false and gives

Call to member function read() on null

But that directory exists and files are there.

Also, Is there any alternative to my above code?

2
  • Is path an absolute path? a relative path? relative to where? Commented Aug 2, 2017 at 9:23
  • Use the is_dir(path); function Commented Aug 2, 2017 at 9:23

4 Answers 4

1

try to use 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

Sign up to request clarification or add additional context in comments.

Comments

1

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 of the files in a directory?

Comments

0

If you take a look into documentation you will see:

Returns an instance of Directory, or NULL with wrong parameters, or FALSE in case of another error.

So Call to member function read() on null means that you got an error (I think that this failed to open dir: No such file or directory in...).

You can use file_exists and is_dir for checking if the given path is a directory and if it really exists.

Example:

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

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

Comments

0

Please check your file path if your path is right. Then please try this code this may help you. Thanks

  <?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);
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.