Mostafa Bayomi
Mostafa Bayomi

Reputation: 13

Read Directories From files, Loop on it and check existence PHP Didn't Work

I am trying to check the existence of directories list on file as below:

<?php
    $file = "L:/tmp/file1.txt";
    $f = fopen($file, "r");
    while ($line = fgets($f,500)) {
        $line = str_replace("\\","/",$line);
        $found=is_dir($strTest);
        if($found) {
          echo "<br>the dir $strTest was found";
        } else {
          echo "<br>the dir $strTest was not found";
       }            
    }
?>

the File I read from like this:

L:\tmp\Folder1
L:\tmp\Folder2
L:\tmp\Folder3
L:\tmp\Folder4

The result is All Folders Not found except the last one .... but I am sure that all the list are exist

Upvotes: 0

Views: 68

Answers (2)

Laz  Karimov
Laz Karimov

Reputation: 714

The problem is that in first folder names

L:\tmp\Folder1
L:\tmp\Folder2
L:\tmp\Folder3

when you use fgets it takes \n as well. So in these names you have next line symbol. In the last one L:\tmp\Folder4 there is no \n, so thats why the only found is the last one.

<?php
$file = "file.txt";
$f = fopen($file, "r");
while ($line = fgets($f, 500)) {    
    $line = str_replace("\\", "/", $line);
    $line = preg_replace("/
/", "", $line);
    if (is_dir($line)) {
        echo "<br />the dir $line was found";
    } else {
        echo "<br />the dir $line was not found";
    }

} ?>

Upvotes: 1

axel
axel

Reputation: 4127

try with this code (replace your parameters)

$handle = opendir('/path/to/directory')

if ($handle) {
    while (false !== ($file = readdir($handle))) {
        print "$file<br />\n";
    }
    closedir($handle);
}

Upvotes: 0

Related Questions