简体   繁体   中英

How to sort a list of files build up with PHP opendir() and hide extensions?

As I only get one very very tiny part of the PHP phenomenon I'm very happy that I managed to create the following script by searching the web. As you can see, this shows the files present in the folder 'archive' on the website I'm building. It's for the newspaper of my school. The old papers will be uploaded to this folder. A problem is that the order is very messy at the moment. I know PHP can sort things with sort(), but I'm not sure how to do that in this case. Could anyone explain how to get it fixed?

Another thing is hiding the extensions. I couldn't find it yet, is there a possibility for that?

You'd be a great help if you could help me at least with the first thing :)

<?php
    if ($handle = opendir(archive)) {
        $ignore_files = array('.', '..', '.htaccess', '.htpasswd', 'index.php');
        while (false !== ($file = readdir($handle)))
        {
            if (!in_array($file, $ignore_files))
            {
                $thelist .= '<a href="/archive/'.$file.'">'.$file.'</a>'.'<br>';
            }
        }
        closedir($handle);
    }
?>
<p><?=$thelist?></p>

If you want to get the list of files from a directory, (and then sort that list), also stripping off the extension, you would do this:

<?php
// $archive variabe assumed to point to '/archive' folder
$ignore_files = array('.', '..', '.htaccess', '.htpasswd', 'index.php');

// into array $files1 will be every file inside $archive:
$files1 = scandir($archive);
sort($files1);

foreach ($files1 as $file) {
    if (!in_array($file, $ignore_files)) {
        $fileParts = pathinfo($file);
        $thelist .= '<a href="/archive/'.$file.'">'.$fileParts['filename'].'</a>'.'<br>';
    }
}
?>
<p><?=$thelist?></p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM