Iterate through text file and check if file exist on server

410 Views Asked by At

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"; }      
}
2

There are 2 best solutions below

0
On BEST ANSWER

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";
    }
}
0
On

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