How to list only PDF documents in PHP?

Asked

Viewed 485 times

-2

I have a code that is listing the files within a certain folder, and linking to download, working all right.

However, I would need this code to list only files with the format *.pdf, the code is this:

<?php 

$diretorio = getcwd(); // pega o endereco do diretorio 
$ponteiro  = opendir($diretorio); // ponteiro que ira percorrer a pasta 



while ($nome_itens = readdir($ponteiro)) { // monta o vetor com os itens da pasta 
    $itens[] = $nome_itens; 
} 
sort($itens); // ordena o vetor de itens 
foreach ($itens as $listar) {  //percorre o vetor para fazer a separacao entre arquivos e pastas 
   if ($listar!=".php" && $listar!=".."){ // retira os itens "./" e "../" para que retorne apenas pastas e arquivos 
           if (is_dir($listar)) { // checa se é uma pasta 
            $pastas[]=$listar; // caso VERDADEIRO adiciona o item ao vetor de pastas 
        } else{  
            $arquivos[]=$listar;// caso FALSO adiciona o item ao vetor de arquivos 
        } 
   } 
}    


$exte_p = array("pdf","PDF");


//foreach($pastas as $listar){// lista as pastas 
   //print "<a href='$listar'><img border=0 src='index_pasta.png'>$listar</a><br>";} 
//

   foreach($arquivos as $listar){// lista os arquivos 
    print "<a href='$listar'>$listar</a><br>";
   

   }

?>

  • You can use the function glob() for this purpose. See manual.

2 answers

2

You can use the function:

glob ( string $pattern [, int $flags = 0 ] ) : array 

for this purpose and specify what type of file pattern you want, which in case would be PDF.

Take an example:

foreach (glob("*.pdf") as $arquivo) {
    echo "arquivo $arquivo\n";
}

See the manual to learn more about this function.

  • Thank you very much, thank you very much for your help

2

I managed to solve with the following code:

<?php
foreach (glob("*.pdf") as $arquivo) {
    echo "<a href='$arquivo'>$arquivo</a><br>" ;        
}
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.