List files from a folder / directory in PHP of certain extensions

10

I need to list the files in a folder, and display them by name linked to their directory to download .

I use this code:

$pasta = 'uploads/';
$arquivos = glob("$pasta{*.jpg,*.JPG,*.png,*.gif,*.bmp}", GLOB_BRACE);
foreach($arquivos as $img){
   echo $img;
}

So far so good. but it displays the directory and the complete file like this:

uploads/editail1.jpg

and I wanted it to display only the file name.

    
asked by anonymous 16.01.2016 / 13:10

1 answer

14

Using your code:

chdir( 'pasta_desejada' );
$arquivos = glob("{*.png,*.jpg,*.jpeg,*.bmp,*.gif}", GLOB_BRACE);
foreach($arquivos as $img) echo $img;

Using the default functions for PHP directories:

$types = array( 'png', 'jpg', 'jpeg', 'gif' );
if ( $handle = opendir('pasta_desejada') ) {
    while ( $entry = readdir( $handle ) ) {
        $ext = strtolower( pathinfo( $entry, PATHINFO_EXTENSION) );
        if( in_array( $ext, $types ) ) echo $entry;
    }
    closedir($handle);
}    

It has this possibility too:

$types = array( 'png', 'jpg', 'jpeg', 'gif' );
$path = 'pasta_desejada';
$dir = new DirectoryIterator($path);
foreach ($dir as $fileInfo) {
    $ext = strtolower( $fileInfo->getExtension() );
    if( in_array( $ext, $types ) ) echo $fileInfo->getFilename();
}

See the 3 code snippets that work at IDEONE .


Notes:

  • In PHP < 5.3.6, the 3rd example needs to be changed:

    $ext = strtolower( pathinfo( $fileInfo->getFilename(), PATHINFO_EXTENSION) );
    
  • In the case of the 2nd and 3rd examples, do not put the same extension in uppercase and lowercase. Only lowercase, since strtolower is already normalizing file extensions.

16.01.2016 / 13:18