0

I have successfully written code to delete the oldest file in a directory if the total number of files exceeds 10. The code below works fine:

<?php
function countFolder($dir) {
 return (count(scandir($dir)) - 2);
}
$fileCount = countFolder('/homepages/mypath/toc');
if ($fileCount > 10)
{
$files = glob('toc/*.txt'); 
rsort($files); 
$oldest = array_pop($files); 
if (!unlink($oldest))
  {
  echo ("Error deleting $oldest");
  }
else
  {
  echo ("Deleted $oldest");
  }
} else {
    echo ("Nothing to delete");
}
?>

But I am having trouble getting the code to repeat if there are more than 11 files in the directory. I want to delete the oldest files only to get down to 10 files. Here is where I am at in attempting to loop the code, but it does not work.

Edit: I moved $filecount into the deleteFiles() function. Still not working.

Is repeating a function even the best way to do what I am attempting?

<?php
function countFolder($dir) {
 return (count(scandir($dir)) - 2);
}

function deleteFiles() {
$fileCount = countFolder('/homepages/mypath/toc');
if ($fileCount > 10)
{
$files = glob('toc/*.txt'); 
rsort($files); 
$oldest = array_pop($files); 
if (!unlink($oldest))
  {
  echo ("Error deleting $oldest");
  }
else
  {
  echo ("Deleted $oldest");
    deleteFiles();
  }
} else {
  echo ("Nothing to delete");
}
}

?>

SOLVED: I finally got this code to work:

<?php
function countFolder($dir) {
return (count(scandir($dir)) - 2);
}
do {
$fileCount = countFolder('/homepages/mypath/toc');

if ($fileCount > 10)
{
$files = glob('toc/*.txt'); 
rsort($files); 
$oldest = array_pop($files); 

if (!unlink($oldest))
  {
  echo ("Error deleting $oldest");
  }
else
  {
  echo ("Deleted $oldest");
    //countFolder();
  }
} else {
  echo ("Nothing to delete");
}
} while ($fileCount > 10);
?>
user1218172
  • 193
  • 1
  • 12
  • `$fileCount` does not exist inside the `deleteFiles()` scope –  Jan 03 '17 at 04:14
  • Isn't $filecount in the global scope though? – user1218172 Jan 03 '17 at 04:18
  • I don't think this is simply a duplicate of a question about scope, as my method of deleting files by repeating a function may be flawed, and I would appreciate feedback on that. – user1218172 Jan 03 '17 at 04:23
  • no its not in global scope. noting in the function will run as non existent $fileCount will never be greater than 10 –  Jan 03 '17 at 04:27
  • Thanks. I have tried putting everything into one function to be in the same scope, but am still not getting success. – user1218172 Jan 03 '17 at 04:46

0 Answers0