Managing limited number of files in directory

Managing limited number of files in directory

We can manage the amount of files in a particular directory using the following function. Every time a new file is uploaded the oldest one must be removed (using the unlink() function) if a maximum limit is already reached. The second parameter is optional and will set the limit whenever the check must happen or not.

<?php
function get_oldest_file($directory) {
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if (is_file($directory.$file)) { // add only files to the array (ver. 1.01)
$files[] = $file;
}
}
if (count($files) <= 12) {
return;
} else {
foreach ($files as $val) {
if (is_file($directory.$val)) {
$file_date[$val] = filemtime($directory.$val);
}
}
}
}
closedir($handle);
asort($file_date, SORT_NUMERIC);
reset($file_date);
$oldest = key($file_date);
return $oldest;
}
// this example will show you the oldest file if there are more then 10 in the dir
echo get_oldest_file(”/path/to/directory/”, 10);
?>

Leave a Reply


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.