ZipStream\ZipStream::addFileFromStream PHP Method

addFileFromStream() public method

dds an open stream to the archive uncompressed
public addFileFromStream ( String $name, Resource $stream, array $opt = [] ) : void
$name String - path of file in archive (including directory).
$stream Resource - contents of file as a stream resource
$opt array - Hash of options for file (optional, see "File Options" below). File Options: time - Last-modified timestamp (seconds since the epoch) of this file. Defaults to the current time. comment - Comment related to this file. Examples: // create a temporary file stream and write text to it $fp = tmpfile(); fwrite($fp, 'The quick brown fox jumped over the lazy dog.'); // add a file named 'streamfile.txt' from the content of the stream $x->addFile_from_stream('streamfile.txt', $fp);
return void
    public function addFileFromStream($name, $stream, $opt = array())
    {
        $block_size = 1048576;
        // process in 1 megabyte chunks
        $algo = 'crc32b';
        $meth = 0x0;
        $genb = 0x8;
        $crc = $zlen = $len = 0;
        $hash_ctx = hash_init($algo);
        // send local file header.
        $num_bytes_written = $this->addFileHeader($name, $opt, $meth, $crc, $zlen, $len, $genb);
        $readError = false;
        // Read data in chunks and send it to the output as soon as it comes in.
        while (!feof($stream)) {
            // Read and send.
            $data = fread($stream, $block_size);
            // Exist if fread failed, and flag the error for post-handling.
            if ($data === false) {
                $readError = true;
                break;
            }
            $this->send($data);
            // Update crc and data lengths.
            hash_update($hash_ctx, $data);
            $len += strlen($data);
            $zlen += strlen($data);
        }
        // Calculate the actual crc.
        $crc = hexdec(hash_final($hash_ctx));
        // Send the data descriptor right after sending the data content.
        // Now we know the actual content len, zlen and crc.
        $data_descriptor_len = $this->addDataDescriptorHeader($len, $zlen, $crc);
        // Calculate how many bytes have been written in total.
        $num_bytes_written += $zlen + $data_descriptor_len;
        // add to central directory record and increment offset
        $this->addToCdr($name, $opt, $meth, $crc, $zlen, $len, $num_bytes_written, $genb);
        // If there was a read error, we still want the cdr to be appended, this way we ensure
        // the zip file can be opened if the exception thrown below is handled by the invoker.
        // E.g, in the catch block, we could add an explanatory 'ERROR.txt' so the enduser knows
        // something went wrong. If this error handling is not performed, the end user can potentially
        // end with a valid zip file but with incomplete or missing files.
        if ($readError) {
            throw new StreamNotReadableException($name);
        }
    }

Usage Example

 /**
  * Stream a zip file to the client
  *
  * @param String $filename  - Name for the file to be sent to the client
  * @param Array  $params    - Optional parameters
  *  {
  *    expiration: '+10 minutes'
  *  }
  */
 public function send($filename, $params = array())
 {
     // Set default values for the optional $params argument
     if (!isset($params['expiration'])) {
         $params['expiration'] = '+10 minutes';
     }
     // Initialize the ZipStream object and pass in the file name which
     //  will be what is sent in the content-disposition header.
     // This is the name of the file which will be sent to the client.
     $zip = new ZipStream\ZipStream($filename);
     // Get a list of objects from the S3 bucket. The iterator is a high
     //  level abstration that will fetch ALL of the objects without having
     //  to manually loop over responses.
     $result = $this->s3Client->getIterator('ListObjects', $this->params);
     // We loop over each object from the ListObjects call.
     foreach ($result as $file) {
         // We need to use a command to get a request for the S3 object
         //  and then we can get the presigned URL.
         $command = $this->s3Client->getCommand('GetObject', array('Bucket' => $this->params['Bucket'], 'Key' => $file['Key']));
         $signedUrl = $command->createPresignedUrl($params['expiration']);
         // Get the file name on S3 so we can save it to the zip file
         //  using the same name.
         $fileName = basename($file['Key']);
         // We want to fetch the file to a file pointer so we create it here
         //  and create a curl request and store the response into the file
         //  pointer.
         // After we've fetched the file we add the file to the zip file using
         //  the file pointer and then we close the curl request and the file
         //  pointer.
         // Closing the file pointer removes the file.
         $fp = tmpfile();
         $ch = curl_init($signedUrl);
         curl_setopt($ch, CURLOPT_TIMEOUT, 120);
         curl_setopt($ch, CURLOPT_FILE, $fp);
         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
         curl_exec($ch);
         curl_close($ch);
         $zip->addFileFromStream($fileName, $fp);
         fclose($fp);
     }
     // Finalize the zip file.
     $zip->finish();
 }
All Usage Examples Of ZipStream\ZipStream::addFileFromStream