Search for a specific file name in a specific folder in laravel

678 Views Asked by At

everyone. So, what I basically want to do is to search for all files that start with "dm" or end with ".tmp" in storage_path("app/public/session").

I already tried File::allFiles() and File::files() but what I get is all files that are into that session folder and I can't figure out how to do it. What I could find in here is questions on how to empty a folder but that's not what I am looking for. Thanks.

2

There are 2 best solutions below

0
codenathan On

Try this code :

$files = File::allFiles(storage_path("app/public/session"));
$files = array_filter($files, function ($file) {
    return (strpos($file->getFilename(), 'dm') === 0) || (substr($file->getFilename(), -4) === '.tmp');
});

Or you can use the glob function like this :

$files = array_merge(
    glob(storage_path("app/public/session/dm*")),
    glob(storage_path("app/public/session/*.tmp"))
);
0
RickDB On

In Laravel, you can use the File facade's glob() method to search for files that match a certain pattern. The glob() function searches for all the pathnames matching a specified pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells.

You can use the glob() method to search for files that start with "dm" or end with ".tmp" in the "app/public/session" directory like this:

use Illuminate\Support\Facades\File;

$storagePath = storage_path("app/public/session");

// Find files that start with "dm"
$files = File::glob("$storagePath/dm*");

// Find files that end with ".tmp"
$files = File::glob("$storagePath/*.tmp");

You can also use the ? and [] wildcard characters, for example ? matches one any single character and [] matches one character out of the set of characters between the square brackets, to search for files that match more specific patterns, like this:

// Find files that starts with "dm" and ends with ".tmp"
$files = File::glob("$storagePath/dm*.tmp");
Note that, File::glob() method return array of matched path, you can loop and see the files or use it according to your needs.