список файлов в папке, показывающей index.php


У меня есть этот код, но он показывает index.php сам по себе, как я могу фильтровать файлы *.php?

<?php
    if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle)))
    {
        if ($file != "." && $file != "..")
        {
            $thelist .= '<LI><a href="'.$file.'">'.$file.'</a>';
        }
    }
    closedir($handle);
    }
?>

<P>Dir:</p>
<UL>
<P><?=$thelist?></p>
</UL>

Также есть ли способ отсортировать их по времени модификации или создания?

 3
Author: cMinor, 2013-03-21

4 answers

Вот еще один, который использует функции ksort или krsort (проверено).
(См. Комментарии в коде.)

<?php
// you can add to the array
$ext_array = array(".htm", ".php", ".asp", ".js"); //list of extensions not required
$dir1 = "."; 
$filecount1 = 0; 
$d1 = dir($dir1);

while ($f1 = $d1->read()) { 
$fext = substr($f1,strrpos($f1,".")); //gets the file extension
if (in_array($fext, $ext_array)) { //check for file extension in list
continue;
}else{
if(($f1!= '.') && ($f1!= '..')) { 
if(!is_dir($f1)) $filecount1++;

$key = filemtime($f1);
$files[$key] = $f1 ;
} 
}
}

// use either ksort or krsort => (reverse order)
//ksort($files);
krsort($files);

foreach ($files as $f1) {
$thelist .= '<LI><a href="'.$f1.'">'.$f1.'</a>';
}

?>

<P>Dir:</p>
<UL>
<P><?=$thelist?></p>
</UL>
 2
Author: Funk Forty Niner, 2013-03-21 20:52:48

Просто добавьте еще одно исключение в ту часть, где вы игнорируете "." и "..", например:

if ($file != "." && $file != ".." && !preg_match('/\.php$/i', $file))

Это исключит любой файл с .php в конце.

 2
Author: Mark Stanislav, 2013-03-21 18:55:21
<?php
    if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle)))
    {
        if ($file != "." && $file != ".." && substr(strrchr($file,'.'),1) != 'php')
        {
            $thelist .= '<LI><a href="'.$file.'">'.$file.'</a>';
        }
    }
    closedir($handle);
    }
?>
 1
Author: digiogi, 2013-03-21 18:57:39

(Кое-что, что я построил)
Это покажет вам имя файла с расширением вместе с количеством файлов (проверено)

<?php
// you can add to the array
$ext_array = array(".htm", ".php", ".asp", ".js");
//list of extensions not required (above)
$dir1 = "."; 
$filecount1 = 0; 
$d1 = dir($dir1); 

while ($f1 = $d1->read()) { 
$fext = substr($f1,strrpos($f1,".")); //gets the file extension
if (in_array($fext, $ext_array)) { //check for file extension in list
continue;
}else{
if(($f1!= '.') && ($f1!= '..')) { 
if(!is_dir($f1)) $filecount1++;

$thelist .= '<LI><a href="'.$f1.'">'.$f1.'</a>';

} 
}
}

// add text and count number below files
echo "Total files in folder: ";
echo "$filecount1";
?>

<P>Dir:</p>
<UL>
<P><?=$thelist?></p>
</UL>
 1
Author: Funk Forty Niner, 2013-03-21 19:14:55