PHP scandir filtered by name

2

I'm trying to do a scandir of a directory that will be filtered by a variable that contains the filename (without the extension) but I have no idea how to accomplish this, here's 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 the scandir to get the file extension because as I said above the variable $nome has no extension, if there is another way to get the full name of the specified file would help a lot too !

    
asked by anonymous 08.02.2018 / 15:58

1 answer

4

You can 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 glob (me) I find it simpler, but it is possible with scandir too. To do this, simply use the 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"
}
    
08.02.2018 / 16:17