2

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"; }      
}
Panos Kalatzantonakis
  • 12,525
  • 8
  • 64
  • 85
Philip
  • 23
  • 6
  • maybe you get newlines appended to the file name? – Ronald Dec 20 '17 at 11:52
  • 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 – NashPL Dec 20 '17 at 11:53

2 Answers2

2

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";
    }
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
0

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

NashPL
  • 461
  • 1
  • 4
  • 19