Listing files from a directory that start with a given text

Asked

Viewed 25 times

0

I am working on the development of a page in html/PHP in which the goal is to perform the search for information on 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 have relation to filtered processes. All files are listed in the same directory and each file has its name started 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 case number).

Basically, I need a code example that allows me to relate the files to download on the page based on this name start, keeping in mind that I work with variables in php for the year and the desired process number. To try to make understanding easier, suppose from the universe of files I have in the directory, I want to relate all that start with "2018_10_" to display on the page and download it.

I hope I’ve been clear enough. Thank you.

2 answers

0

With scandir() - List the files that are in the specified path and within the foreach put a conditional to display only those that have the specified string 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 director which provides a simple interface for viewing contents of file directories

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

0


Can use glob(), being like this:

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

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

That $ano . '_' . $mes . '_*.zip' would result in this 2018_10_*.zip', being the * the wildcard character, that is between the 2018_10_ and the .zip may contain anything.

Browser other questions tagged

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