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?
source to share
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 */
}
}
source to share
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 to share
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?
source to share
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);
?>
source to share