Return to Snippet

Revision: 15288
at June 30, 2009 01:49 by cshaiku


Initial Code
function listFiles($dir)
{
  $output = '';  $outRows = '';  $files = array();
  if (is_dir($dir)) {
    if ($dirHandle = opendir($dir)) {
      $files = array_diff(scandir($dir), array('.', '..', '.htaccess'));
      $totalSize = (int) 0;
      foreach($files as $file) {
        $fileTime = @date("d-M-Y", filectime($dir . '/' . $file)) . ' ' . @date("h:i", filemtime($dir . '/' . $file));
        $totalSize += filesize($dir . '/' . $file);
        $fileSize = @byte_convert(filesize($dir . '/' . $file));
        $cellLink = '<td class="list_files_table_file_link"><a href="/fake/files/' . $file . '">' . $file . '</a></td>';
        $cellTime = '<td>' . $fileTime . '</td>';
        $cellSize = '<td>' . $fileSize . '</td>';
        $outRows .= '<tr>' . "\n  " . $cellLink . "\n  " . $cellTime . "\n  " . $cellSize . "\n" . '</tr>' . "\n";
      }
      closedir($dirHandle);
    }
  }
  $output = '<table class="list_files_table" width="100%" align="center" cellpadding="3" cellspacing="1" border="0">' . "\n";
  $output .= '<thead><tr><td><b>Name</b></td><td><b>Last Modified</b></td><td><b>Size</b></td></tr></thead>' . "\n";
  $output .= '<tfoot><tr><td colspan="2">' . count($files) . ' files.</td><td>' . @byte_convert($totalSize) . '</td></tr></tfoot>' . "\n";
  $output .= '<tbody>' . "\n";
  $output .= $outRows;
  $output .= '</body>' . "\n";
  $output .= '</table>';

  return $output;
}

function byte_convert($bytes)
{
  $symbol = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
  $exp = (int) 0;
  $converted_value = (int) 0;
  if ($bytes > 0) {
    $exp = floor(log($bytes)/log(1024));
    $converted_value = ($bytes/pow(1024,floor($exp)));
  }
  return sprintf('%.2f ' . $symbol[$exp], $converted_value);
}

echo listFiles('/path/to/files');

Initial URL
http://code.cshaiku.com/code_php_list_files.php

Initial Description

                                

Initial Title
Simple File Directory Listing Table

Initial Tags
table, file, directory

Initial Language
PHP