Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class zip {
- // Additional arguments passed to zip binary
- protected $zipArgs;
- // Source file or directory
- protected $src;
- // Destination file (the .zip file)
- protected $dst;
- // Process ID of the zip process
- protected $pid=0;
- // Console output of the zip process.
- // NOTE: If the command is successfull the file will be deleted
- protected $consoleOut;
- // Success state cache
- protected $success=null;
- // Constructor
- function __construct($src, $dst, $zipArgs='') {
- if (!file_exists($src))
- throw new Exceprion("File ${file} does not exist");
- elseif (file_exists($dst) && !is_writeable($dst))
- throw new Exceprion("File ${dst} is not writeable");
- elseif (!file_exists($dst) && !is_writeable(dirname($dst)))
- throw new Exceprion("File ${dst} cannot be created");
- $this->src=$src;
- $this->dst=$dst;
- }
- // Execute the zip command
- // The command wil build the zip and write its output to a tempfile
- // If everything getting fine, the tempfile will be removed. This allows
- // yo to check if the command was successfully.
- // Return integer pid
- public function zip() {
- $this->success=null;
- $this->consoleOut=tempnam(sys_get_temp_dir(), 'Zip');
- if (is_dir($this->src)) {
- $this->zipArgs .= ' -r'; // rkursive pack dirs
- }
- // echo $cmd;
- $cmd = sprintf(
- 'zip %s %s %s > %s 2>&1 && rm -f %s > /dev/null 2>&1 & echo $!',
- $this->zipArgs,
- $this->dst,
- $this->src,
- $this->consoleOut,
- $this->consoleOut
- );
- return $this->pid = shell_exec($cmd);
- }
- // Blocking function, waiting until the zip command has finished
- // return boolean success state
- public function waitForFinish($ms=500) {
- while(1) {
- if (!$this->isRunning()) return $this->isSuccess();
- // Reset time limit
- set_time_limit(ini_get('max_execution_time'));
- usleep($ms);
- }
- }
- // Check if the command is still running
- // return boolean
- public function isRunning()
- {
- $cmd=sprintf('ps -p %d > /dev/null 2>&1', $this->pid);
- $exit=false;
- system($cmd, $exit);
- if ($exit === 0) return true;
- else return false;
- }
- // Check if the command was successfull
- // return boolean
- public function isSuccess()
- {
- if ($this->success !== null)
- return $this->success;
- elseif ($this->pid === 0)
- throw new Exception('No zip file created jet');
- elseif ($this->isRunning())
- return false;
- else
- return !file_exists($this->consoleOut);
- }
- // Get the the command output (stdout&stderr).
- // File is only available on failure
- public function getOutput() {
- if ($this->pid === 0)
- throw new Exception('No zip file created jet');
- elseif (!file_exists($this->consoleOut))
- return 'OK';
- else
- return file_get_contents($this->consoleOut);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement