Why does this code work on only the last directory listed in the file dirs.txt
instead of working on every directory listed in that file. It seems to ignore the foreach
statment until the while
loop ends.
<?php
$handle = fopen("dirs.txt", "r");
$tmpDir = "/tmp/";
if ($handle) {
while (($dir = fgets($handle)) !== false) {
foreach(glob($dir."*love*.mp3") as $file) {
if (!copy($file, $tmpDir.basename($file))) {
echo "Cant copy $file...\n";
}
}
}
} else {
}
fclose($handle);
?>
File dirs.txt is new line separated dirs list
/home/mp3/
/home/music/
/etc/find/music/
I cant see any error, just last dir is processing. All directory is good and files exist inside, and all of them i can open manualy. If i delete /etc/find/music/ from file then /home/music/ will be done
I suspect that fgets
is returning each line from your file with the newline character(s) still attached to the end of the string. But your last string (assuming you don't enter a blank line at the end of the file) would not include a newline character. If this is the case, then possibly the glob
method is trying to find files within a directory path which is being broken into two by a newline character, something like this:
/home/mp3/
*love*.mp3
which is not going to match correctly. So the glob
function returns an empty array, which gives the foreach loop nothing to work on, and so the while
loop skips round to the next line of your file, hitting the same problem until the last line of the file, which does not end with a newline character.
Try inserting this as the first line of your while
loop:
$dir = trim($dir);
That should remove any newline character and make the string suitable for use in the glob
function.