Dominykas55
Dominykas55

Reputation: 1231

PHP creating zip archive adds local disk

I want to export all my images in a zip, but for some reason it adds all of my local disk too... I dont understand..

This is the code:

$files = $urls;
$zipname = 'uploads.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);

foreach ($files as $file) {
    $name = explode( '/', $file);
    $zip->addFile($file, pathinfo( $file, PATHINFO_BASENAME ));
}

$zip->close();

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));

readfile($zipname);

$files is an array of the location of the image:

ServicesController.php on line 61:
array:3 [▼
  0 => "C:\wamp\www\prjct\app/../../prjct/web/uploads/media/default/0001/15/thumb_14794_default_big.gif"
  1 => "C:\wamp\www\prjct\app/../../prjct/web/uploads/media/default/0001/15/thumb_14794_default_small.gif"
  2 => "C:\wamp\www\prjct\app/../../prjct/web/uploads/media/default/0001/15/thumb_14794_admin.gif"
]

When I opne my zip file i see this:

enter image description here

As you can see there is my local disk witch should not be here..

Upvotes: 2

Views: 328

Answers (1)

elveez
elveez

Reputation: 83

This should work:

$files = $urls;
$zipname = 'uploads.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);

$rootPath = realpath($files);
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file) {
    // Get real and relative path for current file
    $filePath = $file->getRealPath();
    $relativePath = substr($filePath, strlen($rootPath) + 1);

    // non-empty directories would be added automatically
    if (!$file->isDir()){
        // Add current file to archive
        $zip->addFile($filePath, $relativePath);    
    }
}

$zip->close();

Generally, you should to use DIRECTORY_SEPARATOR predefined constant instead of slashes/back slashes. This is especially helpful when developing on a Windows machine.

Generally, when working on Windows, make sure to remove the trailing slash when adding folders to zip - that is what created the local disk in your zip file.

$localDirNoSlashes = rtrim($localDir, DIRECTORY_SEPARATOR);
$zip->addEmptyDir($localDirNoSlashes);

This was driving me crazy for a while until I realized what is going on...

Upvotes: 1

Related Questions