Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    May 2006
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Lists files in dir on page, but needs to sort

    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

    Code:
    <?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>

  • #2
    New Coder
    Join Date
    Nov 2006
    Location
    UK
    Posts
    52
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Try ksort.
    - Mark


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •