<?php
ini_set("memory_limit","16M");
$start_usage = memory_get_usage();
$eol = "\r\n";
 
function random($max, $quantity) {
    $numbers = range(0, $max);
    shuffle($numbers);
    return array_slice($numbers, 0, $quantity);
}
 
$options = $_SERVER['argv'];
if (count($options) == 3) {
	$dir = $options[1];
	$hold = $options[2];
}
else {
	echo "use php test.php folder number_to_keep\n";
	exit;
}
$dir = str_replace('\\', '/', $dir);
 
$di = new RecursiveDirectoryIterator($dir);
foreach (new RecursiveIteratorIterator($di) as $file) {
	$path_parts = pathinfo($file);
	$dirname = $path_parts['dirname'];
	$basename = $path_parts['basename'];
 
	if (is_file($file))  {
		$files[$dirname][] = $dirname."/".$basename;
	}
}
$di = array_keys($files);
$disize = count($di);
 
for ($i=0; $i < $disize; $i++) {
	$size = count($files[$di[$i]]);
	if ($size > $hold) {
		$size--;
		$keep = random($size,$hold);
		for ($j=0; $j < count($keep); $j++) unset($files[$di[$i]][$keep[$j]]);
	}
	else {
		for ($j=0; $j < $size; $j++) unset($files[$di[$i]][$j]);
	}
}
 
$counter=0;
foreach($files as $key => $key_array) {
	foreach($key_array as $key_data => $value) {
		$counter++;
		unlink($value).$eol;
	}
}
 
echo $eol."Number of files deleted: ".$counter.$eol;
$end_usage = memory_get_usage();
$used = $end_usage-$start_usage;
echo "Memory used: ".$used." bytes".$eol;
echo "All done".$eol.$eol;
?>