Recent Posts

PHP Traverse Directory

Sometimes, we need to check or delete some files in our application. In this case, we can traverse the specifying directory to find these files.

Using the conventional way

function traverseDir($dir)
{
	if(!is_dir($dir))  
	{    
		return;
	}
	
	$handle = opendir($dir);
	
	while ($file = readdir($handle))
	{
		if( ($file !='.') && ($file !='..') )
		{
			$target = $dir.DIRECTORY_SEPARATOR.$file;
			
			if(is_file($target))
			{
				echo "file: {$target} \r\n";
			}
			else
			{
				echo "directory: {$target} \r\n";
				
				traverseDir($target);
			}
		}
	}	
	closedir($handle);
}

traverseDir("/var/log/nginx");

Using SPL DirectoryIterator

function traverseDir($dir)
{
	$iterator = new DirectoryIterator($dir);
	
	foreach($iterator as $key => $value)
	{
		if(! $value->isDot())
		{
			$target = $value->getPathname();
			
			if( ($value->isFile()) || ($value->isLink()) )
			{
				echo "file: {$target} \r\n";
			}
			else
			{
				echo "directory: {$target} \r\n";
				
				traverseDir($target);
			}
		}	
	}
}

traverseDir("/var/log/nginx");

 

Share this Post