PHP ZipArchive still remains the path to the file even if the file is added without path

guys! I saw a lot of posts talking about using ZipArchive and how to get rid of the path structure inside the zip.
So, here’s my code:

$zipname = $post->post_title.".zip";
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);

foreach($gallery as $img) {
    $attachment = get_attached_file($img['id']);
    $zip->addFile($attachment, pathinfo($attachment,PATHINFO_BASENAME));
}
$zip->close();

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

The problem is, that the zip file contains an image without path, f.e. /image.jpg and the same image in a multiple directories as it appears on the server /path/to/the/file/image.jpg.

Read More

So, I’m not sure why this is happening. Can somebody help on this?

Related posts

1 comment

  1. Looking at the documentation of addFile:

    $zip->addFile($attachment, pathinfo($attachment,PATHINFO_BASENAME));
    

    pathinfo($attachment,PATHINFO_BASENAME) is returning you the “base name”, that is to say the file name (without the path). The second parameter is the name (with path) of the file IN the zip.

    If you want to keep the complete path structure in your zip, you should remove this parameter:

    $zip->addFile($attachment)
    

Comments are closed.