0

I am facing a critical requirement. Here I have to get binary formatted data from a .zip file provided. I need to get the data that is inside the .zip file, in a binary format to place these into a variable. I am really not sure, if at all this can be done in php or not ?

Santanu
  • 7,764
  • 7
  • 26
  • 24

1 Answers1

0

You would use zip php extension. In some versions of php it's included on core. Check PHP Manual for further details. The zip_open function returns resource handler. With zip_read you can read files on zip and with zip_close destroy resource handler.

These functions was taken from php manual (thanks to bisqwit at iki dot fi). You would use them if for any reason don't have php extension and can't be installed.

<?php
function ShellFix($s)
{
  return "'".str_replace("'", "'\''", $s)."'";
}
function zip_open($s)
{
  $fp = @fopen($s, 'rb');
  if(!$fp) return false;

  $lines = Array();
  $cmd = 'unzip -v '.shellfix($s);
  exec($cmd, $lines);

  $contents = Array();
  $ok=false;
  foreach($lines as $line)  
  {
    if($line[0]=='-') { $ok=!$ok; continue; }
    if(!$ok) continue;

    $length = (int)$line;
    $fn = trim(substr($line,58));

    $contents[] = Array('name' => $fn, 'length' => $length);
  }

  return
    Array('fp'       => $fp,  
          'name'     => $s,
          'contents' => $contents,
          'pointer'  => -1);
}                           
function zip_read(&$fp)
{
  if(!$fp) return false; 

  $next = $fp['pointer'] + 1;
  if($next >= count($fp['contents'])) return false;

  $fp['pointer'] = $next;
  return $fp['contents'][$next];
}
function zip_entry_name(&$res)
{
  if(!$res) return false;
  return $res['name'];
}                           
function zip_entry_filesize(&$res)
{
  if(!$res) return false;
  return $res['length'];
}
function zip_entry_open(&$fp, &$res)
{
  if(!$res) return false;
  $cmd = 'unzip -p '.shellfix($fp['name']).' '.shellfix($res['name']);

  $res['fp'] = popen($cmd, 'r');
  return !!$res['fp'];   
}
function zip_entry_read(&$res, $nbytes)
{
  return fread($res['fp'], $nbytes);
}
function zip_entry_close(&$res)
{
  fclose($res['fp']);
  unset($res['fp']);
}
function zip_close(&$fp)
{
  fclose($fp['fp']);
}

I got'it what you mean, yes it's perfectly possible. You can put the extracted file on file system and read with file_get_content and store it. For example if you gonna make file available for download, send variable content and set appropriate headers. But this wouldn't be necessary cause with zip_entry_read you got file content, it doesn't matter the format.

This link may be would help... convert-binary-data-using-php

rernesto
  • 554
  • 4
  • 11