skip to Main Content

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

Answers


  1. 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"))
    );
    
    Login or Signup to reply.
  2. 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 IlluminateSupportFacadesFile;
    
    $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.
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search