سؤال

I am trying to debug this script to run on localhost. $zip->status returns 0, which, according to The Manual means "no error", yet file_exists() still returns false.

I checked manually and the file does in fact not exist. I am running WAMP on localhost.

Why is this behaving this way? How can I fix it?

Here is my exact code:

$destination = "C:\wamp\www\temp\temp.zip";
$zip = new ZipArchive();
echo var_dump($zip);
echo "<br />";
$zzz = $zip->open($destination, ZipArchive::CREATE);
if($zzz === true) {
    echo "created archive<br />";
}else{
    //Var dump says it's true.. is that not a contradiction??
    echo var_dump($zzz)."<br />Couldn't create zipArchive<br />";
}
//add the files
foreach($_SESSION['images'] as $file) {
    $zip->addFile($file);
}

echo "Files ".$zip->numFiles."<br />Status ".$zip->status."<br />";

$zip->close();

if(!file_exists($destination)){
    echo "destination doesnt exist";        
}

And here is the output of that page..

object(ZipArchive)[1]
  public 'status' => int 0
  public 'statusSys' => int 0
  public 'numFiles' => int 0
  public 'filename' => string '' (length=0)
  public 'comment' => string '' (length=0)


created archive
Files 16
Status 0
destination doesnt exist
هل كانت مفيدة؟

المحلول

Update: After some discussion in chat we found out, that $_SESSION['images'] contains http:// urls but ZipArchive itself does not support adding files from remote sources. If you want to add remote images you'll have to download them before. So we've changed the addFile() related part to:

//add the files
foreach($images as $file) {
    $tmpname = tempnam(sys_get_temp_dir(), 'test');
    file_put_contents($tmpname, file_get_contents($file));
    $zip->addFile($tmpname, basename($file));
    unlink($tmpname);
}

Also there is is a logic error, or better, a typo. Replace

$zzz = $zip->open($destination, ZipArchive::CREATE);
if($zzz !== true) {
    echo "created archive<br />";
} ...

by

$zzz = $zip->open($destination, ZipArchive::CREATE);
if($zzz === true) {
    echo "created archive<br />";
} ...

Further note, that the zip is created in memory and will be written to disk not until calling ZipArchive::close(). Check the first comment on the manual page:

If you have created a zip file and added a file to it without error, yet the ZipArchive::close call fails (with ER_TMPOPEN: "Failure to create temporary file") and the zip file is not created, check to see if your ZipArchive::open call specifies a pathname containing nonexisting directories. If you expect a containing hierarchy of one or more directories, you must create them yourself before using using ZipArchive. You can write a simple function to recurse using dirname to find each parent directory, creating those that don't exist by using mkdir when leaving the recursion.

نصائح أخرى

Probably because you have if($zzz !== true) when it should be if($zzz === true). xD

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