繁体   English   中英

将图像以zip格式保存在php中的自定义文件夹中

[英]save images as zip on a custom folder in php

我试图将图像保存在zip文件中,我的代码工作正常,但将所有图像保存在/ wp-content / uploads / 2016/03 / ...文件夹中,我想在zip上拥有自己的“ images”文件夹上面有所有内容...我尝试了在stackoverflow上发布的其他解决方案,但我无法使其正常工作

我的代码:

<?php
//This script is developed by www.webinfopedia.com
//For more examples in php visit www.webinfopedia.com
function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
    $zip = new ZipArchive();
    //create the file and throw the error if unsuccessful
    if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
        exit("cannot open <$archive_file_name>\n");
    }
    //add each files of $file_name array to archive
    foreach($file_names as $files)
    {
        $zip->addFile($file_path.$files,$files);
        //echo $file_path.$files,$files."<br />";
    }
    $zip->close();
    //then send the headers to foce download the zip file
    header("Content-type: application/zip"); 
    header("Content-Disposition: attachment; filename=$archive_file_name"); 
    header("Pragma: no-cache"); 
    header("Expires: 0"); 
    readfile("$archive_file_name");
    exit;
}


//------------------------------------------------------------------------------------------------------
//If you are passing the file names to thae array directly use the following method
$file_names = array('../wp-content/uploads/2016/03/IMG_8121-900x1200.jpg','../wp-content/uploads/2016/03/IMG_8124-900x1200.jpg','../wp-content/uploads/2016/03/IMG_8106-900x1200.jpg');

//------------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------------



//Archive name
$archive_file_name=$name.'DEMOphpCreateZipTodownloadMultipleFiles.zip';
//Download Files path
$file_path=$_SERVER['DOCUMENT_ROOT'].'/images/';

//cal the function
zipFilesAndDownload($file_names,$archive_file_name,$file_path);
?>

只需更改:

$zip->addFile($file_path.$files,$files);

变成:

$zip->addFile($file_path.$files, 'pictures' . DIRECTORY_SEPARATOR . pathinfo($files)['basename']);

addFile方法的第二个参数是文件在归档文件中的外观,因此您可以定义新路径和文件名。

如果我做对了,您想在zip存档中找到文件夹“ images”。

尝试这样的事情:

public function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
    $zip = new \ZipArchive();
    //create the file and throw the error if unsuccessful
    if ($zip->open($archive_file_name, ZipArchive::CREATE )!==TRUE) {
        exit("cannot open <$archive_file_name>\n");
    }
    $zip->addEmptyDir("images");        
    //add each files of $file_name array to archive
    foreach($file_names as $files)
    {
        $zip->addFile($file_path.$files, "images".DIRECTORY_SEPARATOR.$files);
    }
    $zip->close();
    ...
}

它将空文件夹广告到您的zip中,然后在添加foreach循环时在zip中指定文件路径

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM