Link to home
Start Free TrialLog in
Avatar of Kpomilla
Kpomilla

asked on

PHP List Files in a Directory

The below code (from an earlier post) properly lists files in a directory...

I would like to include in the file list the file create date if possible. How would I do that?


<?php
$count = 0;
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {$count++;
            print("<a href=\"".$file."\">".$file."</a><br />\n");
        }
    }
echo '<br /><br /><a href="..">Return</a>';
    closedir($handle);
}
?>

Open in new window

Avatar of Beverley Portlock
Beverley Portlock
Flag of United Kingdom of Great Britain and Northern Ireland image

I answered a similar question some time ago. You should be able to adapt this code to do what you want

https://www.experts-exchange.com/questions/26304778/PHP-Directory-List-Group-and-Sort.html#33130659
Just noticed that there is additional code that you will need in an earlier posting higher up that page

https://www.experts-exchange.com/questions/26304778/PHP-Directory-List-Group-and-Sort.html#33128995

Sorry for the confusion
here you go;
<?php
$count = 0;
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {$count++;
            print date ("F d Y H:i:s", filemtime($file)). ("  <a href=\"".$file."\">".$file."</a><br />\n");
          
        }
    }
echo '<br /><br /><a href="..">Return</a>';
    closedir($handle);
}
?>

Open in new window

Avatar of Kpomilla
Kpomilla

ASKER

Darren-w: Thanks for that...very simple to use. Only issue now: is there a way the info can be tabbed to view in even columns?
You can see this script in action here:
http://www.laprbass.com/RAY_EE_RSS_news_index.php

This lists all the PDF files in a working directory in order by date descending.  Note line 26, where we use this function:
http://us3.php.net/manual/en/function.filemtime.php

You might also want to know about this function:
http://us3.php.net/manual/en/function.filectime.php

HTH, ~Ray
<?php // RAY_EE_RSS_news_index.php
error_reporting(E_ALL);
date_default_timezone_set('America/Chicago');

// THE PATH TO OUR CURRENT WORKING DIRECTORY
$dir = getcwd();

// APPEND A SLASH IF NEEDED
if ($dir[strlen($dir)-1] != DIRECTORY_SEPARATOR) $dir .= DIRECTORY_SEPARATOR;

// AGGREGATE THE DIRECTORY INFORMATION INTO AN ARRAY OF ARRAYS
if ($dh = opendir($dir))
{
    $dir_datas = array();
    while ($file_name = readdir($dh))
    {
        // WE ONLY WANT TO CONSIDER FILES NAMED LIKE *.PDF
        $ext = end(explode('.', $file_name));
        $ext = strtoupper($ext);
        if ($ext == 'PDF')
        {
            $my_name = $dir . $file_name;
            $my_data = array
            ( 'name' => $file_name
            , 'size' => filesize($my_name)
            , 'time' => date('c', filemtime($my_name))
            )
            ;
            $dir_datas[] = $my_data;
        }
    }
}

// IF NO PDFS
if (empty($dir_datas)) die();

// CALL THE FUNCTION TO SORT THE ARRAY BY THE filemtime()
usort($dir_datas, 'timesort');

// GET THE URL PATH
$poz = strrpos($_SERVER["PHP_SELF"], DIRECTORY_SEPARATOR);
$urp = substr($_SERVER["PHP_SELF"], 0, $poz) . DIRECTORY_SEPARATOR;

// CREATE LINKS TO EACH OF THE FILES
$out = NULL;
foreach ($dir_datas as $pdf)
{
    $out .= $pdf["time"];
    $out .= ' ';
    $out .= '<a target="pdf" href="'
    . $urp
    . $pdf["name"]
    . '">'
    . $pdf["name"]
    . '</a>'
    . ' '
    . showfilesize($pdf["size"])
    . '<br/>'
    . PHP_EOL
    ;
}

// CREATE AND DISPLAY THE VIEW OF THE DIRECTORY
$htm
= '<h1>'
. "PUBLICATIONS: "
. date('F j, Y')
. '</h1>'
. $out
;
echo $htm;
die();




// A USER SORT FUNCTION TO ORDER BY DATETIME DESC
function timesort($a, $b, $key='time')
{
    if ($a[$key] == $b[$key]) return 0;
    return ($a[$key] > $b[$key]) ? -1 : 1;
}

// FUNCTION TO PRODUCE AN EASY-TO-READ DESCRIPTION OF THE SIZE OF A FILE
function showFileSize ($xb)
{
    $pb = 1024*1024*1024*1024*1024;
    $tb = 1024*1024*1024*1024;
    $gb = 1024*1024*1024;
    $mb = 1024*1024;
    $kb = 1024;
    if     ($xb >= $pb) { $text = number_format(($xb / $pb),3) . " PB"; }
    elseif ($xb >= $tb) { $text = number_format(($xb / $tb),2) . " TB"; }
    elseif ($xb >= $gb) { $text = number_format(($xb / $gb),1) . " GB"; }
    elseif ($xb >= $mb) { $text = number_format(($xb / $mb),1) . " MB"; }
    elseif ($xb >= $kb) { $text = number_format(($xb / $kb),0) . " KB"; }
    elseif ($xb >= 0)   { $text = number_format( $xb       ,0) . " bytes"; }
    else                { $text = "0 bytes"; }
    return $text;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of darren-w-
darren-w-
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Works great! Thanks everyone for your help.
Darren-
I have an interesting issue I just noticed...The date of a new file appears as 12/31/1969 instead of today's date. Any thoughts?
"date of a new file appears as 12/31/1969"

That's a good example of why you ought to test the solutions before you award the points.  If you had tested the code I posted at ID:35181679 you would have found the correct dates.

I think you might want to post a new question in the PHP Zone to ask what the date of 12/31/1969 means.

Good luck with your project. ~Ray
will check out now
Ok,

I have just tested  the script out on a IIS5.1 (PHP Version 5.3.3) and Apache version 2.2.12 (PHP Version 5.2.10-2ubuntu6.7) and in both cases it comes up with the correct results?  I've also had a read of the filemtime function (http://php.net/manual/en/function.filemtime.php ) and there are no reported errors, please ensure that your webserver software is uptodate and php, and that the time is set correctly on your server.

Darren