I have a peice of PHP script which loops through a directory and looks for filenames present in both the directory and column 1-6 in a CSV file. If it finds one, it checks column 0 of the same row to see if a "Primary" version of the file exists. If it does, it deletes the "secondary" file it's evaluating.
<?php
chdir('../'); // Go up a directory
$fileArray = array_values(preg_grep('/^(\.|\.\.|Removed)$/', scandir('.') , PREG_GREP_INVERT));
foreach ($fileArray as $thisFile)
{
if (preg_match('/^.*?(?=\.[a-zA-Z0-9]+$)/', $thisFile, $thisFileNoExtension)) // Preg Match the file extension
{
$thisFileNoExtension = $thisFileNoExtension[0]; // Give the file extension it's own string
}
else
{
$thisFileNoExtension = $thisFile; // If it's a directory
}
// Let the user know what file is being evaluated
echo "\033[35m{$thisFileNoExtension} ... \033[0m";
$csvManualRegionDupes = fopen("--- HYPERLINK TO REMOTE GOOGLE SHEETS CSV FILE ---", "r");
while ($csvRow = fgetcsv($csvManualRegionDupes))
{
if (in_array($thisFileNoExtension, array_slice($csvRow, 1, 6)))
{
$fileCheck = preg_grep('/' . preg_quote($csvRow[0]) . '/', $fileArray); //
if ($fileCheck)
{
echo "\033[36mis on the Manual Region Dupes list and primary version detected. Moved to Removed folder.\n\033[0m";
rename("$thisFile", "Removed/$thisFile");
}
else
{
echo "\033[31mis on the Manual Region Dupes list but primary version is missing. Kept for now.\n\033[0m";
continue 2;
}
}
}
fclose($csvManualRegionDupes);
echo "\033[34mScanned and is OK.\n\033[0m";
}
?>
It used to work well, however now that I have put $csvManualRegionDupes
to point towards a remote file, it's taking a long time to get through the loop. I think this is beacuse fopen
and fclose
is being run for every $thisFile
. Is there a way of opening this remote file only once and still completing the foreach
and while
loops properly? I have tried tinkering with it and I keep breaking the functionality.
Many thanks!