I only want to list the images but I also list the subfolders

2

This code lists all the files and folders in my folder, what I want is to just list the images, omitting the subfolders that I have inside that folder, images that I need in the code.

 <?php
function listar_archivos($carpeta){
    if(is_dir($carpeta)){
        if($dir = opendir($carpeta)){
            while(($archivo = readdir($dir)) !== false){
                if($archivo != '.' && $archivo != '..' && $archivo != '.htaccess' && $archivo != '' ){
                    echo '<li><a target="_blank" href="'.$carpeta.'/'.$archivo.'">'.$archivo.'</a></li>';
                }
            }
            closedir($dir);
        }
    }
}

echo listar_archivos('img');
?>
    
asked by Ivan E. Rangel 23.08.2018 в 20:02
source

1 answer

1

Better to detect if it is a file and if it is not a file that begins with '.', that is displayed; in the last if it would go something like:

if (is_file($archivo) && substr($archivo, 0, 1) != '.') {
  echo '<li><a target="_blank" href="'.$carpeta.'/'.$archivo.'">'.$archivo.'</a></li>';
}

I forgot to specify that when using is_file, it is necessary to indicate the entire path of the file so it would be something like

is_file($carpeta.'/'.$archivo)

Since we are supposed to be in a superior directory, it opens a child directory and it is necessary to detect if each of the items within that directory is a valid file.

    
answered by 23.08.2018 / 20:14
source