List Directory Contents

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
typo
Forum Newbie
Posts: 4
Joined: Sun Apr 05, 2009 7:22 am

List Directory Contents

Post by typo »

Total n00b question but I'm using the following script to list the contents of the current directory and output the result:

Code: Select all

// Get this folder and files name.
$this_script = basename(__FILE__);
$this_folder = str_replace('/'.$this_script, '', $_SERVER['SCRIPT_NAME']);
 
// Declare vars used beyond this point.
$file_list = array();
$folder_list = array();
$total_size = 0;
 
// Open the current directory...
if ($handle = opendir('.'))
{
    // ...start scanning through it.
    while (false !== ($file = readdir($handle)))
    {
        // Make sure we don't list this folder, file or their links.
        if ($file != "." && $file != ".." && $file != $this_script && $file != ".DS_Store")
        {
            // Get file info.
            $stat               =   stat($file); // ... slow, but faster than using filemtime() & filesize() instead.
            $info               =   pathinfo($file);
            // Organize file info.
            $item['name']       =   $info['filename'];
            $item['lname']      =   strtolower($info['filename']);
            $item['ext']        =   $info['extension'];
                if($info['extension'] == '') $item['ext'] = '.';
            $item['bytes']      =   $stat['size'];
            $item['size']       =   bytes_to_string($stat['size'], 2);
            $item['mtime']      =   $stat['mtime'];
            // Add files to the file list...
            if($info['extension'] != '')
            {
                array_push($file_list, $item);
            }
            // ...and folders to the folder list.
            else
            {
                array_push($folder_list, $item);
            }
            // Clear stat() cache to free up memory (not really needed).
            clearstatcache();
            // Add this items file size to this folders total size
            $total_size += $item['bytes'];
        }
    }
But instead of listing the contents of the current directory I'd like to list the contents of a sub directory labelled 'uploads'. I also still need the anchor links on each file to link to their location in the sub directory.

Can anyone suggest how I can include a variable/constant to specify the sub directory and output & link it's contents?

Thanks
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: List Directory Contents

Post by Mark Baker »

Code: Select all

 
$subdirectory = './mySubDir';
if ($handle = opendir($subdirectory))
 
typo
Forum Newbie
Posts: 4
Joined: Sun Apr 05, 2009 7:22 am

Re: List Directory Contents

Post by typo »

Thanks for the quick reply. I was just playing around with that variable as your answer came in. Out of interest, what does the preceeding '.' do?

Code: Select all

$upload_dir = './uploads/';
if ($handle = opendir($upload_dir))
The only problem I found however was that this then messed up the file size and date data. Every file in the directory displayed as 0 bytes and 3 decades old. By adding this variable to the $stat and $info variables like this:

Code: Select all

// Get file info.
$stat           =   stat($upload_dir.$file);
$info       =   pathinfo($upload_dir.$file);
It then corrected the size and date info. However the file links don't point to the upload directory. The path up to the site root is correct but it just doesn't add in the extra directory. Which bit do I need to change (presumably by appending the $upload_dir variable)?

Thanks
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: List Directory Contents

Post by Mark Baker »

typo wrote:Out of interest, what does the preceeding '.' do?
The preceding dot means "relative to the current directory"

If upload dir is './uploads'
then

Code: Select all

 
$stat  =   stat($upload_dir.'/'.$file);
$info  =   pathinfo($upload_dir.'/'.$file);
 
typo
Forum Newbie
Posts: 4
Joined: Sun Apr 05, 2009 7:22 am

Re: List Directory Contents

Post by typo »

Thanks for the info. I've made the changes to $stat and $info but no change. The output is as before and the links still don't include the '/uploads/' directory in the path.

In the HTML the following outputs the list of files:

Code: Select all

<? if($file_list): ?>
    <? foreach($file_list as $item) : ?>
            <tr class="file">
                <td class="name"><a href="<?=$item['name']?>.<?=$item['ext']?>"><?=$item['name']?>.<?=$item['ext']?></a></td>
                <td class="size"><?=$item['size']['num']?><span><?=$item['size']['str']?></span></td>
                <td class="time"><?=time_ago($item['mtime'])?> old</td>
            </tr>
    <? endforeach; ?>
    <? endif; ?>
In the anchor link it just seems to be linking to the filename of the item of the array and not injecting the path info. Where and how is it best to insert the path info including the $upload_dir?
Post Reply