J.K.A.
J.K.A.

Reputation: 7404

Zip files in folder using PHP

I've a folder which contains all the uploaded files and I am storing path of each file in database according to user id. Now I want to read all files of that particular user and want write all that files into a zipped folder.

How can I do it with PHP?

My code:

// Getting file path here
$data = $model->findAll('tree_parent_id=:id', array(':id' => (int) $model->id));
foreach ($data as $type) {
  print_r($type->path);
}

Upvotes: 0

Views: 1659

Answers (2)

Max Sherbakov
Max Sherbakov

Reputation: 1955

Yii has a zip extension.

 $zip = Yii::app()->zip;
 $zip->makeZip('./','./toto.zip'); // make an ZIP archive 
 $zip->extractZip('./toto.zip', './1/'); // extract Zip arc.

Upvotes: 0

sravis
sravis

Reputation: 3680

I have written function to do it, Which i use it in my projects:

$file: files arary
$zipnam: what to name your zip file
$dir: where to keep your zipped file
$del: should i delete files from source folder after zipping it?

Function:

function zipit($file, $zipnam, $dir, $del=TRUE) {
    $filestozip = $file; // FILES ARRAY TO ZIP
    $dir = trim($dir); // DIR NAME TO MOVE THE ZIPPED FILES
    $zipnam = trim($zipnam);

    $zip = new ZipArchive();
    $files = $filestozip;
    $zip_name = $zipnam.".zip";
    $fizip = $dir.$zip_name;
    if($zip->open($fizip, ZipArchive::CREATE) === TRUE) {
        foreach ($files as $fl) {
          if(file_exists($fl)){
            $zip->addFromString(basename($fl),  file_get_contents($fl));
            if($del === TRUE) {
                unlink($fl);
            }
          }
        }
        $zip->close();
        return TRUE;
    } else { $zip->close(); return FALSE;}
}

Upvotes: 1

Related Questions