开发者

how to create rar/zipfile and download [duplicate]

开发者 https://www.devze.com 2023-01-05 17:27 出处:网络
This question already has answers here: Dynamically creating zip with php (2 answers) Closed 9 years ago.
This question already has answers here: Dynamically creating zip with php (2 answers) Closed 9 years ago.

Hi frnds can anyone tel me how to Create a Zip File Using PHP? Actually i am having 10 files with boxes,if i select more than one che开发者_开发问答ck box that files should get zip/rar and i am able to save that in some path..

Please can anyone help in this solution as i am new to php


$zip_name = 'path/to/final.zip'; //the real path of your final zip file on your system
$zip = new ZipArchive;
$zip->open($zip_name, ZIPARCHIVE::CREATE);
foreach($files as $file)
{
    $zip->addFile($file);
}
$zip->close();

header('Content-type: application/zip');
header('Content-disposition: filename="' . $zip_name . '"');
header("Content-length: " . filesize($zip_name));
readfile($zip_name);
exit();


// This example creates a ZIP file archive test.zip and add the file /path/to/index.txt. as newname.txt. 
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip->addFile('/path/to/index.txt', 'newname.txt');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}


//include your connection file
//$file_names[] get your files array
//$error = "";      //error holder
//$file_path='set your image path' folder to load files
if(extension_loaded('zip'))
{ // Checking ZIP extension is available
    if(count($file_names) > 0)
    {   
        // Checking files are selected
        $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($file_names as $file){  
            $zip->addFile($file_path.$file);            // 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 .= "* Please select file to zip <br/>";
    }
}
else
{
    $error .= "* You dont have ZIP extension<br/>";
}
?>  
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号