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

KpomillaAsked:
Who is Participating?
 
darren-w-Connect With a Mentor Commented:
even columns:
<style type="text/css">
    #date{width:200px;}
    #file{width:200px;}
    #date,#file{float:left;}
</style>
<?php
$count = 0;
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {$count++;
            print "<div id='date'>".date ("F d Y H:i:s", filemtime($file))."</div><div id='file'>". ("  <a href=\"".$file."\">".$file."</a>")."</div><br />\n";
          
        }
    }
echo '<br /><br /><a href="..">Return</a>';
    closedir($handle);
}
?>

Open in new window

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

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_26304778.html#33130659
0
 
Beverley PortlockCommented:
Just noticed that there is additional code that you will need in an earlier posting higher up that page

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_26304778.html#33128995

Sorry for the confusion
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
darren-w-Commented:
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

0
 
KpomillaAuthor Commented:
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?
0
 
Ray PaseurCommented:
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

0
 
KpomillaAuthor Commented:
Works great! Thanks everyone for your help.
0
 
KpomillaAuthor Commented:
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?
0
 
Ray PaseurCommented:
"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
0
 
darren-w-Commented:
will check out now
0
 
darren-w-Commented:
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
0
All Courses

From novice to tech pro — start learning today.