Directory Listing of any website in PHP

Discussion in 'PHP' started by coykiesaol, Apr 9, 2011.

  1. #1
    Hello.

    One of my professors said something vague about how you could use a PHP script to list all the files that are in the same directory as some particular web page.

    I've been trying to figure out how to do this but have had no luck... The only solutions I could figure out were using file handling functions, but whatever I came up with only worked on local directories.

    I get that this might not be possible on most websites because of security reasons, but then there's a lot that I don't know about PHP so I thought I could ask here.

    Is it possible? What would I have to use to do it? Was he joking? :-/

    Thanks!
     
    coykiesaol, Apr 9, 2011 IP
  2. ker

    ker Peon

    Messages:
    97
    Likes Received:
    0
    Best Answers:
    1
    Trophy Points:
    0
    #2
    Yes, of course You can.
    Here is one example:
    <?php
    
    	function directoryToArray($directory, $recursive) {
    	$array_items = array();
    	if ($handle = opendir($directory)) {
    		while (false !== ($file = readdir($handle))) {
    			if ($file != "." && $file != "..") {
    				if (is_dir($directory. "/" . $file)) {
    					if($recursive) {
    						$array_items = array_merge($array_items, directoryToArray($directory. "/" . $file, $recursive));
    					}
    					$file = $directory . "/" . $file;
    					$array_items[] = preg_replace("/\/\//si", "/", $file);
    				} else {
    					$file = $directory . "/" . $file;
    					$array_items[] = preg_replace("/\/\//si", "/", $file);
    				}
    			}
    		}
    		closedir($handle);
    	}
    	return $array_items;
    }
    ?>
    
    PHP:
    Function takes params of directory (String) and recursive (boolean). Recursive means that script is going to open directories and directories in them etc.
    So, you can call this function like following:
    <?php print_r(directoryToArray('/', true));
    PHP:
     
    ker, Apr 9, 2011 IP