PHP将Zip目标创建到不在root上的文件夹

时间:2015-12-18 07:07:03

标签: php zip ziparchive

我有一个代码来创建一个文件夹的zip文件,但zip文件转到root我想在一个文件夹中创建zip,比如" zips"或者不在根目录中的其他东西......这是代码。

//Create Zip
function create_zip($files=Null,$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
    //cycle through each file
    foreach($files as $file) {
        //make sure the file exists
        if(file_exists($file)) {
            $valid_files[] = $file;
        }
    }
}
//if we have good files...
if(count($valid_files)) {
    //create the archive
    $zip = new ZipArchive();
    if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
        return false;
    }
    //add the files
    foreach($valid_files as $file) {
        $new_filename = substr($file,strrpos($file,'/') + 1);
$zip->addFile($file,$new_filename);
    }
    //debug
    //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;

    //close the zip -- done!
    $zip->close();

    //check to make sure the file exists
    return file_exists($destination);
}
else
{
    return false;
}
}

//zip

        $error = "";        //error holder

            $file_folder = "uploads/tracks/";   // folder to load files
            if(extension_loaded('zip')){    // Checking ZIP extension is available
                    $zip = new ZipArchive();            // Load zip library 
                    $zip_name = time().".zip";          // Zip name
                    if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){       // Opening zip file to load files
                        $error .=  "* Sorry ZIP creation failed at this time<br/>";
                    }
                    foreach($post['files'] as $file){               
                        $new_filename = substr($file,strrpos($file,'/') + 1);
 $zip->addFile($file,$new_filename);        // Adding files into zip
                    }
                    $zip->close();
                    if(file_exists($zip_name)){
                        // push to download the zip
                        header('Content-type: application/zip');
                        header('Content-Disposition: attachment; filename="'.$zip_name.'"');
                        readfile($zip_name);
                        // remove zip file is exists in temp path
                        unlink($zip_name);
                    }
            }else
                $error .= "* You dont have ZIP extension<br/>";

    }
}

我想要的只是将zip文件发送到不是根目录的文件夹。

1 个答案:

答案 0 :(得分:0)

function create_zip($ files = Null,$ destination ='',$ overwrite = false) 在$ destination处,提供您要存储文件的位置或文件夹名称。