Solved

PHP List Files in a Directory

Posted on 2011-03-21
11
491 Views
Last Modified: 2013-12-13
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

0
Comment
Question by:Kpomilla
  • 4
  • 3
  • 2
  • +1
11 Comments
 
LVL 34

Expert Comment

by:Beverley Portlock
Comment Utility
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
 
LVL 34

Expert Comment

by:Beverley Portlock
Comment Utility
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
 
LVL 13

Expert Comment

by:darren-w-
Comment Utility
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
 

Author Comment

by:Kpomilla
Comment Utility
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
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 13

Accepted Solution

by:
darren-w- earned 500 total points
Comment Utility
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
 

Author Closing Comment

by:Kpomilla
Comment Utility
Works great! Thanks everyone for your help.
0
 

Author Comment

by:Kpomilla
Comment Utility
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
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
"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
 
LVL 13

Expert Comment

by:darren-w-
Comment Utility
will check out now
0
 
LVL 13

Expert Comment

by:darren-w-
Comment Utility
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

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Router for PHP reqeusts 12 29
XSS cleaning when using ajax & json encode 5 38
resizeing PHP image 2 21
Instering to MySQL table 5 15
Introduction Many web sites contain image galleries; a common design for these galleries includes a page with a collection of thumbnail images.  You can click on each of the thumbnail images to see the larger version of the image.  This is easily i…
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now