Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading all file contents from a directory - php

This is actually is an easy task

I want to display contents of all files located in specified folder.

I am passing directory name

echo "<a href='see.php?qname=". $_name ."'>" . $row["qname"] . "</a>";

on second page ,

I am iterating over the directory content

while($entryname = readdir($myDirectory)) 
{
            if(is_dir($entryname))
            {
                continue;
            }   
            if($entryname=="." || $entryname==".." )
            {}
            else
            {
                if(!is_dir($entryname))
                {   
                    $fileHandle=fopen($entryname, "r");
                    
                    while (!feof($fileHandle) ) {
           $line = fgets($fileHandle);
           echo $line . "<br />";
        }

. . .

but I am unable to read any file , I have changed their permissions as well.

I tried putting directory name statically which worked, Can someone suggest what am I doing wrong?

like image 478
hardik9850 Avatar asked Dec 15 '22 04:12

hardik9850


2 Answers

$entryname will contain JUST the filename, with no path information. You have to manually rebuild the path yourself. e.g.

$dh = opendir('/path/you/want/to/read/');
while($file = readdir($dh)) {
    $contents = file_get_contents('/path/you/want/to/read/' . $file);
                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^---include path here
}

Without the explicit path in your "read the file code", you're trying to open and read a file in the script's current working directory, not the director you're reading the filenames from.

like image 102
Marc B Avatar answered Dec 31 '22 10:12

Marc B


Much simpler:

foreach(glob("$myDirectory/*") as $file) {
    foreach(file($file) as $line) {
        echo $line . "<br />";
    }
}

Even simpler:

foreach(glob("$myDirectory/*") as $file) {
    echo nl2br(file_get_contents($file));
}
like image 44
AbraCadaver Avatar answered Dec 31 '22 09:12

AbraCadaver