I quickly created this script to rename a bunch of files, that was renaming a bunch of files based on the season/episode.
It grabs the directory listing, check the filename and determine which episode number, and rename the file into the same directory.
But sometimes, it would recheck the newly renamed files, essentially twice.
It seemed to happen when the directory had 25 or more files.
code:
$sort_folder = scandir('H:\\Videos\\_Sort\\', 1);
array_pop($sort_folder); // remove .
array_pop($sort_folder); // remove ..
foreach($sort_folder as $folder) {
$n = explode('.', $folder);
$year = str_replace('S', '', $n[2]);
$episodes = $seasons[$year]['episodes']; // array that holds all episode titles, episode number for the season
$numFiles = 0;
if ($handle = opendir('H:\\Videos\\_Sort\\' . $folder)) {
while (false !== ($fileName = readdir($handle))) {
if ($fileName == '.' || $fileName == '..') continue;
echo "\n$fileName:\n";
foreach ($episodes as $e) {
if (strripos($fileName, $e['title']) !== false) {
$numFiles++;
echo $fileName . ' => ' . 'Looney.Tunes.s' . $year . '.e' . sprintf('%02d', $e['epnum']) . '.' . $fileName . "\n";
rename('H:\\Videos\\_Sort\\' . $folder . '\\' . $fileName,
'H:\\Videos\\_Sort\\' . $folder . '\\'
. 'Looney.Tunes.s' . $year . '.e' . sprintf('%02d', $e['epnum']) . '.' . $fileName);
break;
}
}
}
closedir($handle);
if ($numFiles != count($episodes)) {
echo 'Some Files were not renamed';
}
}
}
Some example output:
...Normal Expected renames
102756 Wideo Wabbit MM CN.avi:
102756 Wideo Wabbit MM CN.avi => Looney.Tunes.s1956.e25.102756 Wideo Wabbit MM CN.avi
Looney.Tunes.s1956.e01.011456 Bugs Bonnets MM.mpg:
Looney.Tunes.s1956.e01.011456 Bugs Bonnets MM.mpg => Looney.Tunes.s1956.e01.Looney.Tunes.s1956.e01.011456 Bugs Bonnets MM.mpg
...Goes to rename all the files over again one more time
If I left only 24 files, it would just rename it all once, as expected. Add a 25th file to rename, and it would rename them all twice over.
I was thinking, well, it just grabs the next file in the resource handle, and since files are getting renamed, the newly renamed files will come after the old files are cycled through, since, in the resource (being that same directory), the pointer will point to the new file.
But then wouldn't that happen regardless of how many files in the directory? even if there are 28 files, or 5 files. But it seems to only happen once I reach 25 files in the directory.
I checked PHP docs, but saw nothing there that would hint at this behavior?
Edit: Sorry for the bad title. Hit Submit rather than preview.