Keep x latest files and delete remaining files from particular directory

Friday, July 2, 2010 1:37
Posted in category PHP

Here is the useful code in PHP to keep x latest files and delete remaining files from particular directory

	function delete_old_files($folder_name, $no_latest_files = 10)
	{
		$file_list = array();
		if ($handle = opendir($folder_name)) {
			while (false !== ($file = readdir($handle))) {
				if ($file != "." && $file != "..") {
					$file_list[filemtime($folder_name."/".$file)] = $folder_name."/".$file;
				}
			}
			closedir($handle);
		}

		krsort($file_list);

		$i = 0;
		foreach($file_list as $key => $value)
		{
			$i++;
			if ($i <= $no_latest_files) continue;
			unlink($value);
		}
	}

The above function will loop through the specified folder and add file with file modified time as key and filename as value.
Then it will sort the array based on key and finally it will leave x no. of latest files and delete remaining files in the specified directory.

You can skip to the end and leave a response. Pinging is currently not allowed.

Leave a Reply

*