...

View Full Version : Lists files in dir on page, but needs to sort



druidfog
01-07-2007, 06:12 PM
I have the following code that successfully lists files found in a directory. But, by default it sorts the list by file creation date. How do I make it so that it lists the files in alpha order by filename? Thx



<?php

if (!ereg('/$', $HTTP_SERVER_VARS['DOCUMENT_ROOT']))
define('DIR_FS_ROOT', $HTTP_SERVER_VARS['DOCUMENT_ROOT'].'/');
else
define('DIR_FS_ROOT', $HTTP_SERVER_VARS['DOCUMENT_ROOT']);
define('DIR_FS_FILES', DIR_FS_ROOT.'files/');
//////////////////////////////////////////////////////////////////////////////
// some utilityfunctions
function is_valid_filename($file)
{
$allowed_extensions = array('htm','php','txt');
if ($file{0} == '.')
return false;
$path_parts = pathinfo($file);
if (!in_array(strtolower($path_parts["extension"]), $allowed_extensions))
return false;
return true;
}
function is_valid_file($file)
{
return (is_file(DIR_FS_FILES.$file) && is_writeable(DIR_FS_FILES.$file) && $file{0} != '.' && is_valid_filename($file));
}
//////////////////////////////////////////////////////////////////////////////

$GLOBALS['view'] = 'list';

if ($GLOBALS['view'] == 'list') {
// read dir
$GLOBALS['filelist'] = array();
if ($handle = opendir(DIR_FS_FILES)) {
while (false !== ($file = readdir($handle)))
if (is_valid_file($file))
$GLOBALS['filelist'][] = $file;
closedir($handle);
} else {
trigger_error('cant open filedir');
}
}
?>

<html>
<head>
</head>
<body>

<?php if ($GLOBALS['view'] == 'list') : ?>
<?php if (count($GLOBALS['filelist']) > 0) : ?>
<strong>File List</strong></p>
<ul>
<?php foreach ($GLOBALS['filelist'] as $file) : ?>
<li><a href="?filename=<?=rawurlencode($file)?>"><?=str_replace(".txt", "", $file)?></a></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<?php endif; ?>

</body>
</html>

Linark
01-07-2007, 09:06 PM
Try ksort (http://uk.php.net/manual/en/function.ksort.php).



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum