Why does fgets
and fopen
fail to "open a stream" except for the last line of an input file?
I’m trying to read a file of directory trees and txt files and open each file.
filelist.txt
contains:
a/1600/file.txt
b/1600/file.txt
c/1600/file.txt
Directory:
c/1600/file.txt contains the text directory c
The output in index.php is this:
Warning: file_get_contents(a/1600/file.txt ): Failed to open stream:
No such file or directory in /Users/joe/Sites/php/index.php on line 9Warning: file_get_contents(b/1600/file.txt ): Failed to open stream:
No such file or directory in /Users/joe/Sites/php/index.php on line 9directory c
Why is the contents of only c/1600/file.txt output?
index.php (PHP 8.2):
$handle = fopen("filelist.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$eachfilecontents = file_get_contents($line, true);
echo $eachfilecontents;
}
fclose($handle);
}
2
Answers
I have modify your code to check file before proceed to next
replace your index.php file code with this and it will return you data from all of files.
The relevant part of the error message is No such file or directory. From fgets() documentation:
If last line works, it’s because the file doesn’t have a trailing new line.
You can e.g. trim it yourself:
On a side note, I’m not sure why you’re using the file_get_contents() function with the
use_include_path
flag, it sounds like an unnecessary burden.