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);
?>