1

I am trying to create zip file from specific folder files, it does create the zip file but .env file (i guess any file that starts with dot) will not be include in zip files.

Question

How can I add all files from my folder to zip file regardless of their names?

code

public function downloadZip($fileName)
{
    $zip = new ZipArchive;
    $downloadFolder = 'downloads';
    if (!file_exists($downloadFolder))
    {
        mkdir($downloadFolder);
    }

    if ($zip->open(public_path($downloadFolder.'/'.$fileName.'.zip'), ZipArchive::CREATE) === TRUE)
    {
        $files = File::files(public_path($fileName));
        foreach ($files as $key => $value) {
            $relativeNameInZipFile = basename($value);
            $zip->addFile($value, $relativeNameInZipFile);
        }
        $zip->close();
    }
    return response()->download(public_path($downloadFolder.'/'.$fileName.'.zip'));
}

Screenshot

one

apokryfos
  • 38,771
  • 9
  • 70
  • 114
mafortis
  • 6,750
  • 23
  • 130
  • 288
  • 1
    The second parameter of [files](https://github.com/laravel/framework/blob/9.x/src/Illuminate/Filesystem/Filesystem.php#L561) specifies whether or not to include hidden files, please make sure you are using a decent IDE that can properly typehint your calls – apokryfos Sep 18 '22 at 08:08
  • @apokryfos which part should I check? – mafortis Sep 18 '22 at 08:09
  • @apokryfos this does it `$files = File::files(public_path($fileName), true);` thanks – mafortis Sep 18 '22 at 08:11
  • 1
    @apokryfos you are right, but i do notice on [the contract for laravel 9.x on the docs](https://laravel.com/api/9.x/Illuminate/Contracts/Filesystem/Filesystem.html#method_files) says the second parameter is for `recursive` - which is odd. and they didn't implement the interface. – Bagus Tesa Sep 18 '22 at 08:11
  • @BagusTesa That looks like a bug, the contract named it recursive but the actual implementation implemented differently. Given the implementation change (based on the answer) is from 2016 then I think the contract will need to be changed but I guess that needs to be raised in Github – apokryfos Sep 18 '22 at 08:13
  • Actually I misspoke, the Filesystem interface seems to just be coincidentally named the same as the Filesystem class as the latter does not implement this interface. I can't seem to find anything that implements this interface to be honest. – apokryfos Sep 18 '22 at 08:18

1 Answers1

3

There is just something about it in this git commit.

Git commit of laravel

And in this place they debate about it.

Allow hidden files

You only need to add this to your code:

File::allFiles($directory, $hidden = true)
  • 1
    Thanks, I've updated my code to `$files = File::files(public_path($fileName), true);` and its working now. – mafortis Sep 18 '22 at 08:15
  • 1
    The commit that alters `files` (rather than `allFiles`) is actually not the same one but it happened at around the same time as well – apokryfos Sep 18 '22 at 08:23