php (zip)文件下載設置


普通下載頭大概意思,文件輸出的地方二選一,小文件下載。如文件較大時注意執行時間與內存使用。可以看php大文件下載

$filename = $_GET['filename'];
$pathname = "./sucai/$filename";
$filesize = filesize($pathname);
 
//跟據路徑下載文件
//字節流的方式發送到客戶端
header("content-type:application/octet-stream"); 
//header("content-type:application/force-download");
  
//關於斷點續傳,服務器支持
header("Accept-Ranges:bytes") ;
 
//以附件的形式發送到客戶端
header('Content-Disposition: attachment; filename="' . basename($path) . '"');
 
//文件大小比對
header("Content-Length: ". filesize($path));
 
readfile($path);
 
$handle = fopen($pathname, 'rb');
$content = '';
while (!feof($handle)) {
   $content .= fread($handle, 1024);
}
fclose($handle);
echo $content;

項目中用到zip批量打包下載文件,小文件下載。如文件較大時注意執行時間與內存使用。可以看php大文件下載

$param = [
    'uid'   => 1,
    'title' => $db->escape_string('title','string', 'G'),
    'annex' => $db->escape_string('annex','string', 'G'),
];

RequestCheck::checkParam($param['title'], 'title');
RequestCheck::checkParam($param['annex'], 'annex');

$title = '文檔下載';
$content = serialize($param);

get_logadd(0, $content, $title, 25, $_USER->id);

if (false !== strpos($param['annex'], ',')) {
    $param['annex'] = explode(',', $param['annex']);
} else {
    $param['annex'] = [$param['annex']];
}

if (false !== strpos($param['title'], '.')) {
    $param['title'] = explode('.', $param['title'])[0];
}

$filename = $param['title'] . '_' . date('Y-m-d H-i-s') . '_' . rand(100, 999) . '.zip';

$files = $param['annex'];

$tmpFile = tempnam('./cache', '');

$zip = new ZipArchive;
$zip->open($tmpFile, ZipArchive::CREATE);
foreach ($files as $file) {
    $fileContent = file_get_contents($file);
    $zip->addFromString(basename($file), $fileContent);
}
$zip->close();

header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=' . $filename);
header("Content-Transfer-Encoding: binary"); //告訴瀏覽器,這是二進制文件
header('Content-Length: ' . filesize($tmpFile));
@readfile($tmpFile);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM