php list and link folder’s files

an old way

There is an old way, the following:

<?php
     $path = "./";
     $narray=array();
     $dir_handle = @opendir($path) or die("Unable to open $path");
     echo "";
     $i=0;
     while($file = readdir($dir_handle))
     {
     if($file != '.' && $file != '..' && $file != 'index.php' && $file != 'normal.inc')
     {
     //echo "<a href='$path/$file'>$file</a><br/>";
     $narray[$i]=$file;
     $i++;
     }
     }
     sort($narray);

	   echo "<ul>";	            
     for($i=0; $i<sizeof($narray); $i++)
	   {
	    $filename = str_replace(".html", "", $narray[$i]) & str_replace(".php", "", $narray[$i]);
	   echo "<li><a href='$path$narray[$i]'>$filename</a></li>";
	   }
	   
	   echo "</ul>";
	   //closing the directory
	   closedir($dir_handle);
?>

a new way: glob

<?php
	   echo "<ul>";	  
$phpfiles = glob("[^index]*.php");
foreach ($phpfiles as $phpfile){
     echo '<li><a href="'.$phpfile.'">'.pathinfo($phpfile, PATHINFO_FILENAME).'</a></li>'; 
}	   
	   echo "</ul>";
?>

as you can see, the code is much simpler.

  • With this code: glob(“[^index]*.php”) we have set to list all php files except index.php.
  • with this other: ‘.pathinfo($phpfile, PATHINFO_FILENAME).’ we have set to show only filenames without extension

of course we could set a subfolder as well, with a code like the following:

$phpfiles = glob("[subfolder-name]/[^index]*.php");