Return to Snippet

Revision: 2039
at December 21, 2006 01:57 by mikeejay


Updated Code
/**
 * Delete files in given path (and subdirs)
 *
 * <code> echo deleteFiles('c:/TEMP/greeting/','3019*.vox' ); </code>
 *
 * @param string $path			Path to the files to delete (should end with slash or backslash)
 * @param string $match	 		Filename(s) to delete (use * as wildcard)
 * @param boolean $delSubdirs	Delete matching files in subdirs
 * @return integer				Returns how many files that were deleted
 */
function deleteFiles($path, $match, $delSubdirFiles = false){
	static $deleted = 0;
	$dirs = glob($path."*",GLOB_NOSORT);		// GLOB_NOSORT to make it quicker
	$files = glob($path.$match, GLOB_NOSORT);

	foreach ($files as $file){
		if(is_file($file)){
			unlink($file);
			$deleted++;
		}
	}
	if ($delSubdirFiles) {
		foreach ($dirs as $dir){
			if (is_dir($dir)){
				$dir = basename($dir) . "/";
				deleteFiles($path.$dir,$match);
			}
		}
	}
	return $deleted;
}

Revision: 2038
at December 21, 2006 01:00 by mikeejay


Initial Code
<?
/**
 * Delete files in given path (and subdirs)
 *
 * <code> echo deleteFiles('c:/TEMP/greeting/','3019*.vox' ); </code>
 *
 * @param string $path			Path to the files to delete (should end with slash or backslash)
 * @param string $match	 		Filename(s) to delete (use * as wildcard)
 * @param boolean $delSubdirs	Delete matching files in subdirs
 * @return integer				Returns how many files that were deleted
 */
function deleteFiles($path, $match, $delSubdirFiles = false){
	static $deleted = 0;
	$dirs = glob($path."*",GLOB_NOSORT);		// GLOB_NOSORT to make it quicker
	$files = glob($path.$match, GLOB_NOSORT);

	foreach ($files as $file){
		if(is_file($file)){
			unlink($file);
			$deleted++;
		}
	}
	if ($delSubdirFiles)
	foreach ($dirs as $dir){
		if (is_dir($dir)){
			$dir = basename($dir) . "/";
			deleteFiles($path.$dir,$match);
		}
	}
	return $deleted;
}

Initial URL


Initial Description


Initial Title
Delete files and subdirectory files

Initial Tags


Initial Language
PHP