note 48793 deleted from function.readdir by bjori

From: Date: Sat, 27 May 2006 15:22:40 +0000
Subject: note 48793 deleted from function.readdir by bjori
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-112364@lists.php.net to get a copy of this message
Note Submitter: lars ( at ) noname00 dot org ---- The directory listing snippets here weren't quite what I needed, so I made this. It's collected from bits of various user notes here, so props y'all etc. This pushes directories and files into separate arrays, sorts and prints out hyperlinked and with size information. It omits any unix dotfiles (.bashrc and the like) which are hidden. This can be changed by removing the && $file[0] != "." part from the if clause. Example output: --- Current path: ./example/path Parent directory [ D ] alpha_dir/ [ D ] beta_dir/ [ D ] zigzag_dir/ [ F ] huge.db 123.4 MB [ F ] index.php 123 bytes [ F ] small.db 12.3 KB --- <?php # Do we have a path? if not, it's the current directory $path = $_GET["path"]; if( !isset( $path ) || $path == "" ) { $path = "."; } # Print out for navigation print "Current path: <b>" . $path . "</b><br />"; # Initialise list arrays, directories and files separately and array counters for them $d_arr = array(); $d = 0; $f_arr = array(); $f = 0; # Open possibly available directory if( is_dir( $path ) ) { if( $handle = opendir( $path ) ) { while( false !== ( $file = readdir( $handle ) ) ) { # Make sure we don't push parental directories or dotfiles (unix) into the arrays if( $file != "." && $file != ".." && $file[0] != "." ) { if( is_dir( $path . "/" . $file ) ) # Create array for directories $d_arr[$d++] = $file; else # Create array for files $f_arr[$f++] = $file; } } } } # Wrap things up if we're in a directory if( is_dir( $handle ) ) closedir( $handle ); # Sort and reset the arrays asort( $d_arr ); reset( $d_arr ); asort( $f_arr ); reset( $f_arr ); # Print a parent directory link $d_prev = substr( $path, 0, ( strrpos( dirname( $path . "/." ), "/" ) ) ); print "<a href=\"?path=" . $d_prev . "\"> Parent directory </a><br />\n"; # Print the directory list for( $i=0; $i < count( $d_arr ); $i++ ) { # Print with query string print "[ D ] <a href=\"?path=" . $path . "/" . $d_arr[$i] . "\">" . $d_arr[$i] . "</a>/<br />\n"; } # Print file list for( $i=0; $i < count( $f_arr ); $i++ ) { # Only print path and filename print "[ F ] <a href=\"" . $path . "/" . $f_arr[$i] . "\"> " . $f_arr[$i] . "</a>"; # We may want a file size. NOTE: needs $path to stat if( filesize( $path . "/" . $f_arr[$i] ) >= 1024 ) { # Size in kilobytes print " " . round( filesize( $path . "/" . $f_arr[$i] ) / 1024, 1 ) . " KB<br />\n"; } elseif( filesize( $path . "/" . $f_arr[$i] ) >= 1048576 ) { # Size in megabytes print " " . round( filesize( $path . "/" . $f_arr[$i] ) / 1024 / 1024, 1 ) . " MB<br />\n"; } else { # Size in bytes print " " . filesize( $path . "/" . $f_arr[$i] ) . " bytes<br />\n"; } } ?>

« previous php.notes (#112364) next »