我有一个生成zip文件供下载的脚本。我需要自定义文件名和zip文件名。下载脚本如下:
public function download($jobId, $teacherId){
// define file array
$files = array(
'certificate' => $file_url,
'resume' => $file_url,
'passport' => $file_url,
'degree' => $file_url,
'recommendation' => $file_url
);
// create new zip opbject
$zip = new \ZipArchive();
// create a temp file & open it
$tmp_file = tempnam('.','');
$zip->open($tmp_file, \ZipArchive::CREATE);
// loop through each file
foreach($files as $name => $file){
if (!empty($file)){
// download file
$download_file = file_get_contents($file);
$file_name = $name . '.' . pathinfo($file)['extension'];
// add it to the zip
$zip->addFromString($file_name, $download_file);
}
}
// close zip
$zip->close();
// send the file to the browser as a download
header('Content-disposition: attachment; filename="'. preg_replace('/\s+/','', $teacher->name) .'.zip"'); // $teacher->name = Hoang Hiep
header('Content-type: application/zip');
// Disabled cache
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header('Pragma: private');
readfile($tmp_file);
}
它在我的机器上运行良好(MacOSX)。但它在服务器上无法正常工作。当我在我的服务器上下载时,它总是以zip文件和文件下载名称共享默认文件名:'download.zip'。我期望成为'HoangHiep.zip'(如果$ teacher->名字是Hoang Hiep)。
MacOSX 10.12.1:
PHP 5.6.22 (cli) (built: May 27 2016 12:20:55)
Server version: Apache/2.4.18 (Unix)
Ubuntu 16.04:
PHP 5.6.27-1+deb.sury.org~xenial+1 (cli)
Server version: Apache/2.4.18 (Ubuntu)
我使用了Laravel 5.2。
有什么想法吗?感谢。