I am trying to add an option in a custom Joomla 3.9 component to zip some pdfs and download them from the backend. I used this tutorial. I edited the file defalt.php inside /administrator/components/com_mycomponent/views/item/tmpl/ and added the following:
<?php
if(isset($_POST['create'])){
$zip = new ZipArchive();
$filename = JPATH_ROOT . '/myfolder/myzipfile.zip';
if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
$dir = JPATH_ROOT . '/myfolder/';
// Create zip
createZip($zip,$dir);
$zip->close();
}
// Create zip
function createZip($zip,$dir){
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
// If file
if (is_file($dir.$file)) {
if($file != '' && $file != '.' && $file != '..'){
$zip->addFile($dir.$file);
}
}else{
// If directory
if(is_dir($dir.$file) ){
if($file != '' && $file != '.' && $file != '..'){
// Add empty directory
$zip->addEmptyDir($dir.$file);
$folder = $dir.$file.'/';
// Read data of the folder
createZip($zip,$folder);
}
}
}
}
closedir($dh);
}
}
}
//Download Created Zip file
if(isset($_POST['download'])){
$filename = JPATH_ROOT . '/myfolder/myzipfile.zip';
if (file_exists($filename)) {
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Content-Length: ' . filesize($filename));
flush();
readfile($filename);
// delete file
unlink($filename);
}
}
?>
The zip file is created in the correct location with the correct/expected size but it is either corrupt or empty.
I tried solutions found here in other posts but nothing worked.
Update: I opened the zipped file with 7-zip and found it contains the drive letter where xampp is installed. The myzipfile.zip and all the compressed files were under: G:/xampp/localhost/myjoomlasite/myfolder
Clicking on myzipfile.zip led me in the same path like a loop. Replacing JPATH_ROOT with JPATH_SITE gave the same results.
I hope someone can shed a light on what happened here.