PHP-创建并下载ZipArchive在打开时返回CPGZ


PHP - Create and download ZipArchive returns CPGZ when opening

函数似乎没有正确创建ZIP文件。下载的文件提示工作正常。然而,当打开它时,它只会创建.cpgz格式的副本。

供参考:foreach ($attachments as $file)输出为"/upload/image.jpg"

function downloadAttachment() {
    $zipname = 'attachments.zip';
    $zip = new ZipArchive;
    $zip->open($zipname, ZipArchive::CREATE);
    foreach ($attachments as $file) {
      $fileSrc = $_SERVER['DOCUMENT_ROOT'] . $file["file_attachment"];
      $zip->addFile($fileSrc);
    }
    $zip->close();
    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename='.$zipname);
    header('Content-Length: ' . filesize($zipname));
    ob_clean();
    flush();
    readfile($zipname);
}

您可以使用dirname(__FILE__)-它会返回到当前php脚本的绝对路径,使var_dump( dirname(__FILE__) )查看它给您的内容,然后使用..//folders/..重新定位到您的附件目录

所以您的$zipname将类似于$zipname = dirname(__FILE__) .'/../some_folders/attachements/attachments.zip'

并确保该目录可由www-data用户写入,或者在任何情况下仅由chmod写入0777

__FILE__是PHP的神奇常数之一,您可以在这里查看更多信息-http://php.net/manual/en/language.constants.predefined.php

另一个好的做法是在configs.php中定义包含在每个phpdefine('ROOT_DIR', "absolute root path of your project");中的某个位置,然后在项目中的任何位置使用ROOT_DIR变量作为所有文件夹ROOT_DIR."/folder/file ..."

的前缀