Reading the entire contents of a file from a directory - php

This is actually an easy job. I want to display the contents of all the files located in the specified folder.

I pass the directory name

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

on the second page,

I write

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 can’t read any file, I also changed their permissions

I tried to put the directory name statically and it works, any solution?

+4
source share
2 answers

$entrynamewill contain JUST file name without path information. You must manually rebuild the path yourself. eg.

$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 an explicit path in your "read file code", you are trying to open and read the file in the current working directory of the script, and not in the directory from which you read the file names.

+5

:

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

:

foreach(glob("$myDirectory/*") as $file) {
    echo nl2br(file_get_contents($file));
}
+2

All Articles