PHP: List Files in Directory

      No Comments on PHP: List Files in Directory

The following snippet lists all files and subdirectories in the specified directory. For the files it lists the file size as well. It uses the following functions: opendir, readdir, is_dir, filesize. All the functions are available in PHP4 and PHP5 so the code runs without any problem on PHP4+.

	// Gets the files from a directory
	function getDirectoryList ($directory) 
	{
		// get a directory handler
		if ($handler = opendir($directory)) 
		{
			// iterate through the directory in the correct way
			while (false !== ($file = readdir($handler))) 
			{
				// make sure the current directory and the parent directory are not included in the file list
				if ($file != "." && $file != "..") 
				{
					
					if (is_dir($directory . '/' . $file))
					{
						// if the retrieved item is a directory just list it:
						echo "$file\n";
					}
					else 
					{
						// otherwise get the file size and list the file and its size
						$filesize = filesize($directory . '/' . $file);
						echo "$file:$filesize\n";
					}
				}
			}
			
			// don't forget to close the habdler to clean the resources
			closedir($handler);
		}
	}
  
	// this is how you invoke the function
	getDirectoryList('.');

Leave a Reply

Your email address will not be published. Required fields are marked *