Relate files in a directory that start with a given text

0

I'm working on developing a page in html / PHP where the purpose is to search for information about certain processes.

For each process covered by the search filter, the page displays a set of information.

My goal is to relate files from a specific directory that relate to filtered processes. All files are listed in the same directory, each file having its name beginning with the year and the process number (in this format: yyyy_p_resto-do-nome.zip , where yyyy is the year and p is the process number).

Basically, I need an example code that will allow me to relate the downloadable files to the page based on that name start, keeping in mind that I work with variables in php for the year and the desired process number. To try to make it easier to understand, let's say that from the universe of files I have in the directory, I want to relate all those starting with " 2018_10_ " to display on the page and download it.

I hope it has been clear enough. Thank you.

    
asked by anonymous 22.08.2018 / 20:29

2 answers

0

You can use glob() , thus:

$ano = 2018;
$mes = 10;
$pasta = 'foo/bar/downloads';

foreach (glob($pasta . '/' . $ano . '_' . $mes . '_*.zip') as $arquivo) {
    echo 'Arquivo:', $arquivo, '<br>';
}

This $ano . '_' . $mes . '_*.zip' would result in this 2018_10_*.zip' , being * the wildcard character, ie between 2018_10_ and .zip can contain anything.

    
22.08.2018 / 23:16
0

With scandir () - List the files that are in the path specified and within foreach place a conditional to display only those that have the string specified in the names.

$string = '2018_10_';

$files = scandir('diretorio/');
foreach($files as $file) {
    if (strpos($file, $string) !== false) {
        echo $file;
        /***** disponibiliza para download qualquer tipo de arquivo.
         Se forem .zip não há necessidade do atributo download 
        ****************/
        echo "<a href=\"diretorio/". $file."\" download>". $file."</a>";
        echo "<br>";
    }
}

Or use directoryIterator that provides a simple interface for viewing content of file directories

$dir=new DirectoryIterator("diretorio/");
foreach ($dir as $file) {
    if (strpos($file,"2018_10_")!== false) {
      echo $file . "<br>\n";
    }
}
    
22.08.2018 / 23:07