0

I use the following code to zip the online image and download the zip file to local. But show "file not exist".

$url = "http://www.google.com/intl/en_ALL/images/logo.gif";
$zip = new ZipArchive;
$zipname = sys_get_temp_dir() . "/" . time() . ".zip";
if ($zip->open($zipname, ZipArchive::CREATE) === TRUE) {
  $zip->addFromString('logo.gif', file_get_contents($url));
  $zip->close();
  if (file_exists($zipname)) {
      // force to download the zip
      header("Pragma: public");
      header("Expires: 0");
      header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
      header("Cache-Control: private", false);
      header('Content-type: application/zip');
      header('Content-Disposition: attachment; filename="' . $zipname . '"');
      readfile($zipname);
      // remove zip file from temp path
      unlink($zipname);

      echo "ok";
   } else {
      echo "file not exist";
   }
  } else {
     echo "failed";
}

How do I solve it? Thanks

sKhan
  • 9,694
  • 16
  • 55
  • 53
Howard Hee
  • 909
  • 1
  • 13
  • 29

1 Answers1

0

You need to define $zipname with absolute path to some writable directory. For example you can use sys_get_temp_dir() function to get php temp dir path.

$zipname = sys_get_temp_dir() . "/" . time() . ".zip";

See here more info about sys_get_temp_dir() function:http://php.net/manual/en/function.sys-get-temp-dir.php

Armen
  • 4,064
  • 2
  • 23
  • 40
  • I have tried add the sys_get_temp_dir(), but still "file not exist". sameple zipname as "vfs://root/temp/1456553223.zip" – Howard Hee Feb 27 '16 at 06:09
  • I don't know actually what is `vfs://` but have you changed manually that zip file is there ? – Armen Feb 27 '16 at 08:12
  • "vfs://root/temp/" is the path value of sys_get_temp_dir(). I use console log to view the value of $zipname, so I get "vfs://root/temp/1456553223.zip" – Howard Hee Feb 27 '16 at 09:31
  • Ok so you are telling that when you check it through terminal console you see that file exists in `vfs://root/temp/1456553223.zip` but when you do file_eixists('vfs://root/temp/1456553223.zip') it return false ? can you do var_dump( file_eixists('vfs://root/temp/1456553223.zip') ) what it gives you ? – Armen Feb 28 '16 at 05:32
  • Yes. The return value of var_tump is empty. – Howard Hee Feb 29 '16 at 02:19
  • as you are making var_dump of file_eixists it can't be empty as file_eixists() (here is doc:http://php.net/manual/en/function.file-exists.php) return only `true` or `false`, seems you are doing something wrong ... – Armen Feb 29 '16 at 06:28