Im trying to unpack a zip file with a file.create:after
hook, like this:
'hooks' => [
'file.create:after' => function ($file) {
if (strpos($file->filename(), '.zip') !== false) {
$zip = new ZipArchive;
if ($zip->open($file) === TRUE) {
$zip->extractTo($file->parent()->root());
$zip->close();
// success
} else {
// failed
}
}
}
],
However, it doesn’t get unpacked. Is there a better way?
I just found out that kirby has a helper for zips…
'hooks' => [
'file.create:after' => function ($file) {
if (strpos($file->filename(), '.zip') !== false) {
F::unzip($file, $file->parent()->root());
}
}
],
But that doesn’t do it either… any ideas?
Thanks but it doesnt work even if i take that if statement out.
moeli
5
From my point of view your code looks ok.
Try to add error handling and evaluate the return values.
https://www.php.net/manual/en/ziparchive.open.php
Thanks but doing echo in a hook makes it fail. I dont know how to properly error handle in a hook, it needs to pop a kirby error modal.
moeli
7
You could try to make the unzip part work outside a hook. In a separate script / snippet or whatever you are comfortable with.
Or log the values with https://www.php.net/manual/en/function.error-log.php
Or use file_put_contents() to log in your own logfile https://www.php.net/manual/en/function.file-put-contents.php
Or check your browsers network tab where the echoed part shows up.
Or throw an Exception which should open the error modal.
Ah ha! This does it…
'hooks' => [
'file.create:after' => function ($file) {
if (strpos($file->filename(), '.zip') !== false) {
$zipfile = $file->filename();
$zipath = $file->parent()->root();
$zipsrc = $zipath.'/'.$zipfile;
F::unzip($zipsrc, $zipath);
}
}
],
moeli
9
You can use $file->root()
instead.
And I can only recommend to add error handling to your code.
You can use $file->extension() like
if ($file->extension() == 'zip') {
[Changed]
in php the extension is without .
in Windows it is with a .
moeli
11
I don’t think the dot is added to the extension.
if ($file->extension() == 'zip') {
1 Like