Wednesday, September 24, 2008

php function zip and stream 2

last time we use ziparchive but now
we'll use zip library from phpmyadmin
and never store data on server

function zipAndStream($filestostream,$dir,$flag=0){
  require_once("zip.lib.php"); // from phpmyadmin
  $zip = new zipfile();
    if(is_array ($filestostream)){
      foreach($filestostream as $filetostream){
        $filename = $dir."/".$filetostream;
        $fsize = @filesize($filename);
        $fh = fopen($filename, 'rb', false);
        $filedata = fread($fh, $fsize);
        $zip->addFile($filedata,$filename);
        $filecount++;
        $filenamefull = $filetostream;
        $filename = substr($filetostream,0,strrpos($filetostream,'.'));
      }
      if($filecount!=1){
        $filename = $filecount.'files';
      }
    }else{
      $filename = $dir."/".$filestostream;
      $fsize = @filesize($filename);
      $fh = fopen($filename, 'rb', false);
      $filedata = fread($fh, $fsize);
      $zip->addFile($filedata,$filename);
      $filecount++;
      $filename = substr($filestostream,0,strrpos($filestostream,'.'));
    }
  $zipcontents = $zip->file();
  if($flag==1){
    $imagefile = "php.png";
    $filesize = strlen($zipcontents)+filesize($imagefile);
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"".$filecount."files_".$imagefile."\"");
    header("Content-length: " . $filesize . "\n\n");
    readfile($imagefile);
  }elseif($flag==-1){
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"".$filenamefull."\"");
    header("Content-length: " . strlen($filedata) . "\n\n");
    echo $filedata;
    exit;
  }else{
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"".$filename.".zip\"");
    header("Content-length: " . strlen($zipcontents) . "\n\n");
  }
  echo $zipcontents;
}