سؤال

I am creating a zip archive in php and want to add some pdf files available in my pdfs_lib folder.I have successfully created the archive but there is a problem that inside the created zip archive, files get added into pdfs_lib folder, which is not what i want.

I want to add pdf files present in pdfs_lib folder directly into the archive instead of adding those files inside pdfs_lib folder in my created zip archive.

What i have tried is:

    // Create Zip File
    $zip = new ZipArchive;
    $res = $zip->open("pdfs_lib/my_zip_archive.zip", ZipArchive::CREATE);
    if ($res === TRUE)
    {
        // Add pdf file to zip archive
        $zip->addFile("pdfs_lib/pdf_file_1.pdf");
        $zip->addFile("pdfs_lib/pdf_file_2.pdf");

        $zip->close();
        echo 'ok';
    } else {
        echo 'failed';
    }

This code creates the zip archive successfully but whwen i unzip the archive it creates a pdfs_lib folder and unzip all files inside this newly created folder.

Any suggestion on how to create a zip archive without add pdf_lib folder in it.

هل كانت مفيدة؟

المحلول

Change the addFile calls to:

$zip->addFile("pdfs_lib/pdf_file_1.pdf", "pdf_file_1.pdf");

The second parameter is the 'localname', the name used in the zipfile itself. If you leave out the folderpath there, it will be added to the root in the zipfile.

نصائح أخرى

A side not as an into: usually it is considered good practice if an archive (be it zip or any other archive format) unpacks into a clean folder instead of littering the contained files all over the place.

However if you really want to implement this without such folder, then you must rework your code. You have two alternatives:

  1. you can change the working directory your php script is executed in into that folder where you keep the files in. In that case you do not need any path to add files to the zip archive, thus no folder is constructed inside the archive.

  2. the addFile() method of phps zip extension allows to specify a second (optional) argument which allows to pass the target name of a passed file.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top