如何解决php压缩文件失败的问题
导读
PHP实现文件下载功能,提示压缩包损坏及打不开的解决方法
// 文件下载 public static function downFile($id,$admin_id,$cid,$type) { $company = checkAdminCompany($admin_id,$cid); if (!$company) { return [ 'status' => -4, 'statusMsg' => '公司不存在' ]; } if ($type=='file') { // 判断是否有权限下载文件 $checkFileRole = self::checkFileRole($admin_id,$cid,$id); if (!$checkFileRole) { return [ 'status' => 777, 'statusMsg' => '没有操作权限' ]; } $select_sql = "SELECT * FROM cloud_storage WHERE id in ($id)"; send_execute_sql($select_sql,$fileInfo); } elseif ($type == 'list') { // 判断是否有权限移动目录下的文件 $checkRole = self::checkRole($admin_id,$cid,$id); if (!$checkRole) { return [ 'status' => '777', 'statusMsg' => '没有操作权限' ]; } $select_sql = "SELECT * FROM cloud_storage WHERE list_id = $id"; send_execute_sql($select_sql,$fileInfo); } if (empty($fileInfo)) { return [ 'status' => -400, 'statusMsg' => '文件不存在' ]; } foreach ($fileInfo as $key => $value) { $paths[$key] = $fileInfo[$key]['path']; } //这里需要注意该目录是否存在,并且有创建的权限 $filename = 'logs/down/test.zip'; if(!file_exists($filename)){ $zip = new ZipArchive(); if ($zip->open($filename, ZipArchive::CREATE)==TRUE) { foreach( $paths as $val){ if(file_exists($val)){ $zip->addFile( $val, basename($val)); } } $zip->close(); } } if(!file_exists($filename)){ exit("无法找到文件"); } header("Cache-Control: public"); header("Content-Description: File Transfer"); header('Content-disposition: attachment; filename='.basename($filename)); //文件名 header("Content-Type: application/zip"); //zip格式的 header("Content-Transfer-Encoding: binary"); //告诉浏览器,这是二进制文件 header('Content-Length: '. filesize($filename)); //告诉浏览器,文件大小 ob_clean(); flush(); @readfile($filename); unlink($fileurl); exit; }
其实大多数的错误都是在缺少
ob_clean(); flush();
评论(0)