using zipArchive addFile() will not add image to zip

后端 未结 4 988
迷失自我
迷失自我 2021-01-04 14:01

I\'ve been at this for a while. This actually worked one time, then never again. it simply does not create the zip file. The file does exist.

$zip = new          


        
相关标签:
4条回答
  • 2021-01-04 14:14

    I had similar kind of issue and it was related with the file that I was going to add to the zip archive.

    Before adding file to zip archive, it's always better to check if the file exists.

    $thisdir = "$_SERVER[DOCUMENT_ROOT]/zip";
    if (file_exists($thisdir . "/trash-icon.png")) {
        $zip->addFile($thisdir . "/trash-icon.png", "/gabage.png");
    }
    
    0 讨论(0)
  • 2021-01-04 14:16

    The ZipArchive::addFile() method accepts the path to the file as its first parameter, but not all paths are created equal. addFile() method silently rejects the file and you never know what went wrong. As can be derived from the question, an alternative approach would be:

    // $zip->addFile($file);
    $content = file_get_contents($file);
    $zip->addFromString(pathinfo ( $file, PATHINFO_BASENAME), $content);
    

    In addition to getting the code working, file_get_contents() also generates decent error messages.

    0 讨论(0)
  • 2021-01-04 14:28

    See the answer to this question - it also works for images, and uses addFile instead of addFromString, which as far as I know is lighter in memory usage.

    0 讨论(0)
  • 2021-01-04 14:34

    The ZipArchive::addFile() method accepts the path to the file as its first parameter.


    Here, you are using :

    $zip->addFile("/trash-icon.png", "/gabage.png");
    

    Which means you are trying to add the /trash-icon.png file to your archive.


    Are you sure this file exists ?

    Note there is a / at the beginning of that file's path, which indicates it's an absolute path.
    Maybe that / should be removed, to use a relative path ?

    0 讨论(0)
提交回复
热议问题