Solved

PHP List Files in a Directory

Posted on 2011-03-21
11
500 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
  • +1
11 Comments
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 35181540
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
ID: 35181563
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-
ID: 35181590
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
Don't Cry: How Liquid Web is Ensuring Security

WannaCry is just the start. Read how Liquid Web is protecting itself and its customers against new threats.

 

Author Comment

by:Kpomilla
ID: 35181638
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 110

Expert Comment

by:Ray Paseur
ID: 35181679
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
 
LVL 13

Accepted Solution

by:
darren-w- earned 500 total points
ID: 35182105
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
ID: 35184165
Works great! Thanks everyone for your help.
0
 

Author Comment

by:Kpomilla
ID: 35184267
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 110

Expert Comment

by:Ray Paseur
ID: 35184287
"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-
ID: 35184324
will check out now
0
 
LVL 13

Expert Comment

by:darren-w-
ID: 35184418
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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

734 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