Jump to content

[SOLVED] alphabetize


Andrei

Recommended Posts

Hi,

 

I am a total php neophyte. I hope you can help.

 

I am using the following code to display the content of a folder:

 

// Define the full path to your folder from root

$path = "/home/folder01";

 

// Open the folder

$dir_handle = @opendir($path) or die("Unable to open $path");

 

// Loop through the files

while ($file = readdir($dir_handle)) {

 

if($file == "." || $file == ".." || $file == "index.php" || $file == "error_log" || $file == ".htaccess" || $file == "getfile.php" )

 

continue;

echo "<a href=\"$file\">$file</a><br>";

 

}

 

// Close

closedir($dir_handle);

 

At the moment it displays the files randomly and I'd like to see the files alphabetized. Can anyone suggest how to do this?

 

Thank you so much for your help!

 

Link to comment
Share on other sites

glob

 

<?php
$path = "/home/folder01/*";

$files = glob($path);

sort($files);
$badNames = array(".", "..", "index.php", "error_log", ".htaccess", "getfile.php");
foreach ($files as $filename) {
    if (!in_array($filename, $badNames)) {
          echo '<a href="' . $filename . '">' . $filename . '</a><br />';
    }
}
?>

 

Should do it for you.

Link to comment
Share on other sites

<?php
$path = "/home/folder01/*";

$files = glob($path);

sort($files);
$badNames = array(".", "..", "index.php", "error_log", ".htaccess", "getfile.php");
foreach ($files as $filename) {
    $filename = explode("/", $filename);
    $filename = end($filename);
    if (!in_array($filename, $badNames)) {
          echo '<a href="' . $filename . '">' . $filename . '</a><br />';
    }
}
?>

 

Should fix that.

Link to comment
Share on other sites

Or use

 

    $filename = basename($filename);

 

instead of

 

    $filename = explode("/", $filename);
    $filename = end($filename);

 

Same outcome, just a bit shorter. And you can remove the dot and double dot from the $badNames array, since they don't appear when using glob().

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.