PHP scandir filtered by name

Asked

Viewed 239 times

2

I’m trying to make a scandir of a directory that will be filtered by a variable that contains the name of the file (without the extension) however I have no idea how to accomplish this, follows an example:

$nome = $_POST["imgname"];//nome do arquivo recebido pelo post
$dir = "pasta/img/";//Local onde o arquivo está salvo
$arquivo = scandir($dir);//Pedaço que gostaria de modificar para filtrar pelo $nome

OBS: I’m doing scandir to get the file extension because as I said above the variable $nome does not have extension, if there is another way to get the full name of the specified file would help a lot too!

1 answer

4


You can do glob("{$dir}/{$nome}*");, so you can capture the file. Ex:

~/Images
    01.jpg
    02.jpg
    03.jpg
    04.jpg
    05.jpg
    05.png

Php:

<?php

var_dump( glob("~/Images/01*") );

//Output
array(1) {
  [0]=>
  string(14) "~/Images/01.jpg"
}

With the glob (i) I find it simpler, but it is possible with scandir also. For this just use function array_filter

<?php

$files = scandir(__DIR__);

function checkFile($file) {
    return preg_match("/^{$_POST['name']}/", $file);
}

var_dump( array_filter($files, 'checkFile') );

//Output:
array(1) {
  [18]=>
  string(6) "~/Images/01.jpg"
}
  • Simpler than I thought, thanks for the hint, but why put {} in the variables? From what I tested he returned the same value to me with or without them, has some specific reason?

  • @Wel just to improve reading and not to be using "texto" . $var . "texto". This allows me to use "texto{$var}text", so PHP will know the limit of the variable. If there were no {}, PHP would think that the variable is $vartext.

Browser other questions tagged

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