首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在.zip扩展后添加Zip附加代码

在.zip扩展后添加Zip附加代码
EN

Stack Overflow用户
提问于 2015-01-27 21:54:28
回答 2查看 36关注 0票数 0

我想打包一个文件夹,然后下载这个。打包的文件已经创建,但是在文件名后面附加了一个代码,所以当我调用该文件进行下载时,它并不存在,因为“物理上”它们有另一个名称。遵循以下代码:

代码语言:javascript
复制
function zip($source, $destination){
    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
    }

    $source = str_replace('\\', '/', realpath($source));

    if (is_dir($source) === true)
    {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

        foreach ($files as $file)
        {
            $file = str_replace('\\', '/', $file);

            // Ignore "." and ".." folders
            if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
                continue;

            if (is_dir($file) === true)
            {
                $zip->addEmptyDir(str_replace($source . '/', '', $file));
            }
            else if (is_file($file) === true)
            {

                $str1 = str_replace($source . '/', '', '/'.$file);
                $zip->addFromString($str1, file_get_contents($file));

            }
        }
    }
    else if (is_file($source) === true)
    {
        $zip->addFromString(basename($source), file_get_contents($source));
    }

    $zip->close();

    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Content-Type: application/force-download');
    header('Content-Disposition: inline; filename="'.$file_name.'"');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . filesize($destination));
    header('Connection: close');
    readfile($destination);
    exit();

}

readfile($file_name)正在调用filename.zip,但实际名称是filename.zip.06452,所以我得到了一个错误。

EN

回答 2

Stack Overflow用户

发布于 2015-01-27 21:58:30

您应该:

代码语言:javascript
复制
header('Content-Length: ' . filesize($destination));

代码语言:javascript
复制
readfile($destination);

因为那是你写归档文件的地方:

代码语言:javascript
复制
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
...
票数 0
EN

Stack Overflow用户

发布于 2015-01-28 01:51:36

我有办法了!这个文件的末尾有代码,myfile.zip.das87是一个临时文件,它是php在启动打包过程时创建的,完成后将其重命名为myfile.zip。我打印了错误消息并得到了Renaming temporary file failed,所以问题出在文件夹权限上。感谢所有试图帮助我的人。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28172188

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档