Page 1 of 1

help with listing files from server

Posted: Mon May 19, 2008 7:10 am
by zipadee
I'm using this code to list files on my web server:

Code: Select all

<?php 
 
$folder = "articles/";
$handle = opendir($folder);
 
# Making an array containing the files in the current directory:
while ($file = readdir($handle))
{
    $files[] = $file;
}
closedir($handle);
 
#echo the files
foreach ($files as $file) {
    echo "<a href=$folder$file>$file</a>"."<br />";
}
?>
I didn't write the code, I got it from a tutorial. My PHP knowledge is very limited :S

this is probably a dumb question but.... how do I get rid of the links to the directory and only link to the files within it?

also, when I upload a file with space in its name, the link in the list won't work. how do I stop that happening?

thanks.

Re: help with listing files from server

Posted: Mon May 19, 2008 8:59 am
by Glycerine
Not a dumb question at all buddy. Here you go. This is a hacked version of a force download script I made.
If you want that - just ask.

Code: Select all

<?php
 
    //document rooted - for saftey
    $path = $_SERVER['DOCUMENT_ROOT'] . "/articles/";
 
    // Open the folder
    $dir_handle = @opendir($path) or die("Unable to open $path");
    // Loop through the files
    while ($file = readdir($dir_handle)) {
 
    if($file == "." || $file == ".." || $file == "index.php" )
 
        continue;
            //collect the extension (only if you want to.)
            $ext = findexts($file);
            echo $file . ", Extension = " . $ext . "<br>"; 
 
} 
// Close
closedir($dir_handle);
 
//find the extension function. Very useful, works with pretty much anything.
function findexts ($filename){
    $filename = strtolower($filename) ;
    $exts = split("[/\\.]", $filename) ;
    $n = count($exts)-1;
    $exts = $exts[$n];
    return $exts;
} 
?>
 

Re: help with listing files from server

Posted: Mon May 19, 2008 9:19 am
by VladSun
I would recommend using glob

Re: help with listing files from server

Posted: Mon May 19, 2008 9:23 am
by Glycerine
wow. did not know glob existed. Is the pattern pregmatching?

-- WAIT NEVERMIND, I read the rest of the page :crazy:

Re: help with listing files from server

Posted: Mon May 19, 2008 9:30 am
by VladSun
I don't think so:
pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells.
EDIT: I love people that read the man-pages ;)

Re: help with listing files from server

Posted: Mon May 19, 2008 9:39 am
by Glycerine
[crushes can with skull] :banghead: YEEEAAHH!!! [punches someone]