Search code examples
phpreaddiropendir

PHP list file with exception


I have made a PHP page which shows a list of files in one folder. Now that I don't want some one to access this folder directly, I plan to add a PHP script which redirects to index.php. Simply I don't want this file to appear in the list

Can I add exception to this extension only? or any better idea for that?

if ($handle = opendir('manual')) {
    while (false !== ($entry = readdir($handle))) {
           if ($entry != "." && $entry != "..") {
               echo "<a href='manual/$entry' target='_blank'>$entry</><br>";
           }
     }
     closedir($handle);
}

Solution

  • If you don't want your index.php file to be displayed in this list then simply use an if statement.

    if ($handle = opendir('manual')) {
        while (false !== ($entry = readdir($handle))) {
               if ($entry != "." && $entry != "..") {
                   if($entry!='index.php') // Go ahead only if the file is not index.php
                       echo "<a href='manual/$entry' target='_blank'>$entry</a><br>";
               }
         }
         closedir($handle);
    }
    

    And, if you want to hide all the php files, then you can use preg_match:

    if ($handle = opendir('manual')) {
        while (false !== ($entry = readdir($handle))) {
               if ($entry != "." && $entry != "..") {
                   if (!preg_match('/.php/', $entry)) // Go ahead only if the file is not having .php as it's extension
                       echo "<a href='manual/$entry' target='_blank'>$entry</a><br>";
               }
         }
         closedir($handle);
    }