readdir help

Discussion in 'PHP' started by Isaac, Jul 6, 2008.

  1. #1
    Here is the code I am using.

    <?php
    $count = 0;
    if ($handle = opendir('./../downloads/nes')) {
        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);
    }
    ?>
    PHP:
    Why does it not show my results in alphabetical order, and how can I make it do so? I'm trying to create a download script for my site, so that I just upload the files to a directory, and they automatically show up.

    Any help is appreciated.
     
    Isaac, Jul 6, 2008 IP
  2. Danltn

    Danltn Well-Known Member

    Messages:
    679
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    120
    #2
    assign them to an array instead of outputting, then sort($array) and output your HTML from the array.

    Dan
     
    Danltn, Jul 6, 2008 IP
  3. Isaac

    Isaac Peon

    Messages:
    389
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Can you show me how to do that? I tried myself, but can't seem to get it.
     
    Isaac, Jul 6, 2008 IP
  4. php-lover

    php-lover Active Member

    Messages:
    261
    Likes Received:
    21
    Best Answers:
    0
    Trophy Points:
    58
    #4
    From your code it should be display your download file in alphabetical order. But if it doesn't sort then try this code.


    if ($handle = opendir('./../downloads/nes')) {    
    
        while (false !== ($file = readdir($handle))) {        
        
        if ($file != '.' && $file != '..') {             
          
             $file_name[] = basename($file);       
          
          }    
       }
       
       sort($file_name);
       foreach($file_name as $download_file){
       
          print("<a href=\"".$download_file."\">".$download_file."</a><br />\n");
       
       }
       
       echo '<br /><br /><a href="..">Return</a>';    
    
    
    closedir($handle);
    }
    PHP:
     
    php-lover, Jul 6, 2008 IP
    Isaac likes this.
  5. Isaac

    Isaac Peon

    Messages:
    389
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    0
    #5
    That code works perfectly. Thanks for the help.
     
    Isaac, Jul 6, 2008 IP
  6. php-lover

    php-lover Active Member

    Messages:
    261
    Likes Received:
    21
    Best Answers:
    0
    Trophy Points:
    58
    #6
    Glad it's work :)
     
    php-lover, Jul 6, 2008 IP