Anuj TBE
Anuj TBE

Reputation: 9800

php dir function returns null even when files are there

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?

Upvotes: 3

Views: 967

Answers (4)

Neodan
Neodan

Reputation: 5252

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 */
    }
}

Upvotes: 0

Haq Nawaz
Haq Nawaz

Reputation: 482

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

Upvotes: 0

M.suleman Khan
M.suleman Khan

Reputation: 596

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?

Upvotes: 1

yoeunes
yoeunes

Reputation: 2945

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

Upvotes: 1

Related Questions