码迷,mamicode.com
首页 > Web开发 > 详细

PHP中通过ZipArchive批量下载pdf文件

时间:2020-05-01 10:31:28      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:浏览器   强制   creat   UNC   关闭   scan   获取   tin   dir   

PHP中通过ZipArchive批量下载pdf文件

场景

通过点击一个按钮批量下载远程pdf文件

步骤

1.获取远程文件内容,写入临时目录和文件

2.将临时目录打包

3.下载打包文件

4.下载后删除临时文件

代码部分

//文件地址
$file_path = [
    ‘http://localhost:8888/1.pdf‘,
    ‘http://localhost:8888/2.pdf‘,
    ‘http://localhost:8888/3.pdf‘,
    ‘http://localhost:8888/4.pdf‘,
];
//利用ZipArchive实现打包
$zip = new \ZipArchive();
$zip_path = ‘./temp/‘;
$zip_name = ‘temp.zip‘;
$zip_file = $zip_path . $zip_name;
if ($zip->open($zip_file, \ZipArchive::CREATE)) {
    foreach($file_path as $v) {
        //获取文件内容
        $file_content = file_get_contents($v);
        //写入临时文件(没有temp目录的需要先手动创建或用mkdir创建)
        $temp_file_path = $zip_path . ‘temp_‘ . time() . rand(1000, 9999) . ‘.pdf‘;
        //创建临时目录
        if (!is_dir($zip_path)) {
            if ((mkdir($zip_path, 0777, true)) === false) {
                return ‘临时目录创建失败!‘;
            }
        }
        //写入文件
        $temp_file = file_put_contents($temp_file_path, $file_content);
        if (!$temp_file) {
            continue;
        }
        //文件写入zip中
        $zip->addFile($temp_file_path);
    }
    //关闭
    $zip->close();
}

//设置下载zip的头信息
header(‘Content-Type: application/zip‘);        //zip压缩文件
header("Content-Transfer-Encoding: Binary");    //二进制传输
header("Content-Type:application/force-download");  //强制下载
header("Content-Disposition: attachment; filename=" . $zip_name);   //告诉浏览器下载并设置文件名
readfile($zip_file);

//下载后删除临时目录(delete_dir方法见下方)
if (is_dir($zip_path)) delete_dir($zip_path);
/**
 * 删除目录
 */
if (!function_exists(‘delete_dir‘)) {
    function delete_dir($path)
    {
        if (!is_dir($path)) {
            return false;
        }
        $dirs = scandir($path);
        foreach ($dirs as $dir) {
            if ($dir == ‘.‘ || $dir == ‘..‘) {
                continue;
            }
            if (is_dir($path . $dir)) {
                delete_dir($path . $dir);
            } else {
                @unlink($path . $dir);
            }
        }
        @rmdir($path);
    }
}

参考

php中文手册

PHP中通过ZipArchive批量下载pdf文件

标签:浏览器   强制   creat   UNC   关闭   scan   获取   tin   dir   

原文地址:https://www.cnblogs.com/trblog/p/12812531.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!