Reputation: 25
I have a txt file with 40.000 file paths with filenames that I need to check if they exist.
To check for a single file i use the following code:
$filename='/home/httpd/html/domain.com/htdocs/car/002.jpg';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
That code works.
Now I want to iterate through the txt file, that contains one path per row
/home/httpd/html/domain.com/htdocs/car/002.jpg
/home/httpd/html/domain.com/htdocs/car/003.jpg
/home/httpd/html/domain.com/htdocs/car/004.jpg
...
I tried to iterate through the txt file with this code, but i get "file does not exist" for all files.
$file = "list.txt";
$parts = new SplFileObject($file);
foreach ($parts as $filename) {
if (file_exists($filename)) { echo "The file $filename exists"; }
else { echo "The file $filename does not exist"; }
}
Upvotes: 2
Views: 398
Reputation: 94672
Your list.txt
file has a newline at the end of each line. You first need to trim that off before using $filename
in the file_exists()
like this for example
<?php
$file = "list.txt";
$parts = new SplFileObject($file);
foreach ($parts as $filename) {
$fn = trim($filename);
if (file_exists($fn)) {
echo "The file $fn exists\n";
} else {
echo "The file $fn does not exist\n";
}
}
Upvotes: 2
Reputation: 481
when you load a file try to break the string into array by explode() function. Then you will be able to validate with file_exist function
Upvotes: 0