PHP Traverse Directory

By:    Updated: January 24,2017

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("E:\sphinx");

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("E:\sphinx");

 

More in Development Center
New on Valinv
Related Articles
Sponsored Links