Checking folder contents

Discussion in 'PHP' started by enchance, Oct 25, 2007.

  1. #1
    How do I do this in php: retrieve the number of subfolders and their names inside a specified folder, as well as retrieve the number of files as well as their names in that subfolder. I'm making an image gallery for my brother.
     
    enchance, Oct 25, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    Like this?
    
    function dir_get_contents($dir)
    {
    	$dir = rtrim($dir, '/\\');
    
    	if (!$handle = @opendir($dir))
    	{
    		trigger_error("Unable to open directory {$dir}");
    		return false;
    	}
    	
    	$files = array();
    	
    	while (($entry = readdir($handle)) !== false)
    	{
    		if (!in_array($entry, array('.', '..')))
    		{
    			$path = "{$dir}/{$entry}";
    			
    			if (is_file($path))
    			{
    				$files[] = $path;
    			}
    			else if (is_dir($path) AND $tmp = dir_get_contents($path))
    			{
    				$files = array_merge($files, $tmp);
    			}
    		}
    	}
    
    	closedir($handle);
    	return $files;
    }
    
    PHP:

    Usage example:
    
    $files = dir_get_contents('path/to/dir');
    
    echo '<pre>' . print_r($files, true) . '</pre>';
    
    PHP:
     
    nico_swd, Oct 25, 2007 IP
  3. enchance

    enchance Peon

    Messages:
    109
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks a lot. I'll look it over and customize it for my project.
     
    enchance, Oct 26, 2007 IP
  4. grikis

    grikis Banned

    Messages:
    333
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #4
    php.net/scandir
     
    grikis, Oct 26, 2007 IP