Where to store non-page related .php files/ZIP-file creation hook

Hello!

Maybe these are silly questions:

a) if I have a php-file which is called via Fetch POST by click a frontend button, to create a temporary Zip-file from all the files on a subpage, where would I store this php-file? Do I have to create a hidden folder tempziparchives/createzip.php in the content folder? Similar to/like the search folder?

b) In your opinion, would it be kind of overkill – to instead of creating a temporary ZIP-file on click – to create a ZIP-file hook, which would be called everytime after file upload to create a non-temporary ZIP-file (would be overridden each time)?

Thx!

Not into the content folder, no. You can either put it in the project root, or put the code into a route instead.

I’d say that depends on how often images are uploaded and how often the zip file is downloaded and hence the temporary zip file needs to be created. So, whatever creates less load on the server. On the other hand, from a user’s perspective, downloading an existing zip is faster then having to wait for the zip to be created.

Thanks! I’m gonna go with the hook version then.
I’m trying to create the zip-file like this. It works for documents but it can’t really zip images properly. Do you have any idea what’s missing?

 'hooks' => [
      'file.create:after' => function ($file) {
      $page = $file->page();
      
      $pagefiles = $page->files();
      $zip = new ZipArchive();

      $zipfile = $page->uid() . ".zip";
      $zip->open($zipfile, ZipArchive::CREATE | ZIPARCHIVE::OVERWRITE === TRUE);

      foreach ($pagefiles as $pagefile) {
          $finalfile = file_get_contents($pagefile);
          $zip->addFromString(basename($pagefile), $finalfile);
      }
      
      $zip->close();
     }
]

This is what the names of the image files look like. :confused: I also tried toFile() in the foreach loop.

Bildschirmfoto 2020-06-04 um 16.41.50

I think I’d need to repeat the code also for the file update and file delete hook then, since the file list would change then.

Yes, it would probably make sense to wrap the code in a function your can call in each hook to keep the code dry.

Why do you read the file instead of just adding them? Create a Zip File Using PHP

Ah, yeah I thought I had to “download” them because adding doesn’t work. I guess it’s because $zip->addFile($pagefile, $pagefile) is getting the wrong path to the image.

You probably have to pass the file root as argument: https://getkirby.com/docs/reference/objects/file/root

$zip->addFile($pagefile->root(), basename($pagefile->filename()))
Using filename() works

One last question @texnixe, if you allow: where would I declare such a “global” function which I can reuse in different hooks? In a controller?

In a plugin. Put an index.php into a plugins folder in /site/plugins, e.g. /site/plugins/zippy/index.php. Inside that index.php, put your function.

1 Like