1

Donloadscript > Do not display files with a specific extension.

I have a script for downloads in which the following instruction does not show certain files. This also works very well.

while ($file_name = readdir($dir_handle)) {
        // Hide files so only visible files can be downloaded
        if ($file_name != '.access' and $file_name != '.' and $file_name != '.htaccess' and $file_name != 'index.php' and $file_name != '001.php' and $file_name != '002.php' and $file_name != '003.php' and $file_name != '005.php' and $file_name != '007.php' and $file_name != '009.php' and $file_name != '010.php') {
$show_files
}

Question: How to define all PHP files globally instead of having to explicitly define each PHP file like in the posted code? It doesn't work with $file_name != '*.php

Many thanks in advance for tips and hints

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
Fontane
  • 45
  • 4

1 Answers1

1

Since PHP 8 we have str_ends_with which should work for you. That, along with a lookup array for literal files should be enough. See this for a version of str_ends_with for older versions of PHP, although I’d recommend the Symfony polyfill potentially, too, just to have access to other functions.

function shouldFileBeHiddenA(string $file): bool {
    static $knownHiddenFiles = ['.access', '.', '.htaccess'];
    
    if(in_array($file, $knownHiddenFiles)) {
        return true;
    }
    
    if(str_ends_with($file, '.php')) {
        return true;
    }
    
    return false;
}

An alternative is to use the pathinfo function which is probably overkill but might read easier for some people:

function shouldFileBeHiddenB(string $file): bool {
    static $knownHiddenFiles = ['.access', '.', '.htaccess'];
    static $knownHiddenExtensions = ['php'];
    
    if(in_array($file, $knownHiddenFiles)) {
        return true;
    }
    
    if(in_array(pathinfo($file, PATHINFO_EXTENSION), $knownHiddenExtensions)) {
        return true;
    }

    return false;
}

Demo: https://3v4l.org/HiJHe

Chris Haas
  • 53,986
  • 12
  • 141
  • 274