For Programmers: Free Programming Magazines  


Home > Archive > PHP Language > February 2005 > list dir









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author list dir
Mark M...

2005-02-26, 3:55 am

hi all

i have a script that displays files and folders in a given directory.
the problem is when i am at the top of the directory and then click the
"parent directory" link it takes me up to my root folder. anyone have an
idea how to root the folder to a given subdirectory so that it thinks it
is the root? the script is below

<?php

# Do we have a path? if not, it's the current directory
$path = $_GET["path"];
if( !isset( $path ) || $path == "" ) {
$path = "./public";
}

# 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
sort( $d_arr ); reset( $d_arr );
sort( $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";
}
}

?>
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com