VanGans

unzip

Oct 9th, 2018
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 11.33 KB | None | 0 0
  1.  <?php
  2. /**
  3.  * The Unzipper extracts .zip or .rar archives and .gz files on webservers.
  4.  * It's handy if you do not have shell access. E.g. if you want to upload a lot
  5.  * of files (php framework or image collection) as an archive to save time.
  6.  * As of version 0.1.0 it also supports creating archives.
  7.  *
  8.  * @author  Andreas Tasch, at[tec], attec.at
  9.  * @license GNU GPL v3
  10.  * @package attec.toolbox
  11.  * @version 0.1.0
  12.  */
  13. define('VERSION', '0.1.0');
  14.  
  15. $timestart = microtime(TRUE);
  16. $GLOBALS['status'] = array();
  17.  
  18. $unzipper = new Unzipper;
  19. if (isset($_POST['dounzip'])) {
  20.   //check if an archive was selected for unzipping
  21.   $archive = isset($_POST['zipfile']) ? strip_tags($_POST['zipfile']) : '';
  22.   $destination = isset($_POST['extpath']) ? strip_tags($_POST['extpath']) : '';
  23.   $unzipper->prepareExtraction($archive, $destination);
  24. }
  25.  
  26. if (isset($_POST['dozip'])) {
  27.   $zippath = !empty($_POST['zippath']) ? strip_tags($_POST['zippath']) : '.';
  28.   // Resulting zipfile e.g. zipper--2016-07-23--11-55.zip
  29.   $zipfile = 'zipper-' . date("Y-m-d--H-i") . '.zip';
  30.   Zipper::zipDir($zippath, $zipfile);
  31. }
  32.  
  33. $timeend = microtime(TRUE);
  34. $time = $timeend - $timestart;
  35.  
  36. /**
  37.  * Class Unzipper
  38.  */
  39. class Unzipper {
  40.   public $localdir = '.';
  41.   public $zipfiles = array();
  42.  
  43.   public function __construct() {
  44.  
  45.     //read directory and pick .zip and .gz files
  46.     if ($dh = opendir($this->localdir)) {
  47.       while (($file = readdir($dh)) !== FALSE) {
  48.         if (pathinfo($file, PATHINFO_EXTENSION) === 'zip'
  49.           || pathinfo($file, PATHINFO_EXTENSION) === 'gz'
  50.           || pathinfo($file, PATHINFO_EXTENSION) === 'rar'
  51.         ) {
  52.           $this->zipfiles[] = $file;
  53.         }
  54.       }
  55.       closedir($dh);
  56.  
  57.       if (!empty($this->zipfiles)) {
  58.         $GLOBALS['status'] = array('info' => '.zip or .gz or .rar files found, ready for extraction');
  59.       }
  60.       else {
  61.         $GLOBALS['status'] = array('info' => 'No .zip or .gz or rar files found. So only zipping functionality available.');
  62.       }
  63.     }
  64.   }
  65.  
  66.   /**
  67.    * Prepare and check zipfile for extraction.
  68.    *
  69.    * @param $archive
  70.    * @param $destination
  71.    */
  72.   public function prepareExtraction($archive, $destination) {
  73.     // Determine paths.
  74.     if (empty($destination)) {
  75.       $extpath = $this->localdir;
  76.     }
  77.     else {
  78.       $extpath = $this->localdir . '/' . $destination;
  79.       // todo move this to extraction function
  80.       if (!is_dir($extpath)) {
  81.         mkdir($extpath);
  82.       }
  83.     }
  84.     //allow only local existing archives to extract
  85.     if (in_array($archive, $this->zipfiles)) {
  86.       self::extract($archive, $extpath);
  87.     }
  88.   }
  89.  
  90.   /**
  91.    * Checks file extension and calls suitable extractor functions.
  92.    *
  93.    * @param $archive
  94.    * @param $destination
  95.    */
  96.   public static function extract($archive, $destination) {
  97.     $ext = pathinfo($archive, PATHINFO_EXTENSION);
  98.     switch ($ext) {
  99.       case 'zip':
  100.         self::extractZipArchive($archive, $destination);
  101.         break;
  102.       case 'gz':
  103.         self::extractGzipFile($archive, $destination);
  104.         break;
  105.       case 'rar':
  106.         self::extractRarArchive($archive, $destination);
  107.         break;
  108.     }
  109.  
  110.   }
  111.  
  112.   /**
  113.    * Decompress/extract a zip archive using ZipArchive.
  114.    *
  115.    * @param $archive
  116.    * @param $destination
  117.    */
  118.   public static function extractZipArchive($archive, $destination) {
  119.     // Check if webserver supports unzipping.
  120.     if (!class_exists('ZipArchive')) {
  121.       $GLOBALS['status'] = array('error' => 'Error: Your PHP version does not support unzip functionality.');
  122.       return;
  123.     }
  124.  
  125.     $zip = new ZipArchive;
  126.  
  127.     // Check if archive is readable.
  128.     if ($zip->open($archive) === TRUE) {
  129.       // Check if destination is writable
  130.       if (is_writeable($destination . '/')) {
  131.         $zip->extractTo($destination);
  132.         $zip->close();
  133.         $GLOBALS['status'] = array('success' => 'Files unzipped successfully');
  134.       }
  135.       else {
  136.         $GLOBALS['status'] = array('error' => 'Error: Directory not writeable by webserver.');
  137.       }
  138.     }
  139.     else {
  140.       $GLOBALS['status'] = array('error' => 'Error: Cannot read .zip archive.');
  141.     }
  142.   }
  143.  
  144.   /**
  145.    * Decompress a .gz File.
  146.    *
  147.    * @param $archive
  148.    * @param $destination
  149.    */
  150.   public static function extractGzipFile($archive, $destination) {
  151.     // Check if zlib is enabled
  152.     if (!function_exists('gzopen')) {
  153.       $GLOBALS['status'] = array('error' => 'Error: Your PHP has no zlib support enabled.');
  154.       return;
  155.     }
  156.  
  157.     $filename = pathinfo($archive, PATHINFO_FILENAME);
  158.     $gzipped = gzopen($archive, "rb");
  159.     $file = fopen($filename, "w");
  160.  
  161.     while ($string = gzread($gzipped, 4096)) {
  162.       fwrite($file, $string, strlen($string));
  163.     }
  164.     gzclose($gzipped);
  165.     fclose($file);
  166.  
  167.     // Check if file was extracted.
  168.     if (file_exists($destination . '/' . $filename)) {
  169.       $GLOBALS['status'] = array('success' => 'File unzipped successfully.');
  170.     }
  171.     else {
  172.       $GLOBALS['status'] = array('error' => 'Error unzipping file.');
  173.     }
  174.  
  175.   }
  176.  
  177.   /**
  178.    * Decompress/extract a Rar archive using RarArchive.
  179.    *
  180.    * @param $archive
  181.    * @param $destination
  182.    */
  183.   public static function extractRarArchive($archive, $destination) {
  184.     // Check if webserver supports unzipping.
  185.     if (!class_exists('RarArchive')) {
  186.       $GLOBALS['status'] = array('error' => 'Error: Your PHP version does not support .rar archive functionality. <a class="info" href="http://php.net/manual/en/rar.installation.php" target="_blank">How to install RarArchive</a>');
  187.       return;
  188.     }
  189.     // Check if archive is readable.
  190.     if ($rar = RarArchive::open($archive)) {
  191.       // Check if destination is writable
  192.       if (is_writeable($destination . '/')) {
  193.         $entries = $rar->getEntries();
  194.         foreach ($entries as $entry) {
  195.           $entry->extract($destination);
  196.         }
  197.         $rar->close();
  198.         $GLOBALS['status'] = array('success' => 'Files extracted successfully.');
  199.       }
  200.       else {
  201.         $GLOBALS['status'] = array('error' => 'Error: Directory not writeable by webserver.');
  202.       }
  203.     }
  204.     else {
  205.       $GLOBALS['status'] = array('error' => 'Error: Cannot read .rar archive.');
  206.     }
  207.   }
  208.  
  209. }
  210.  
  211. /**
  212.  * Class Zipper
  213.  *
  214.  * Copied and slightly modified from http://at2.php.net/manual/en/class.ziparchive.php#110719
  215.  * @author umbalaconmeogia
  216.  */
  217. class Zipper {
  218.   /**
  219.    * Add files and sub-directories in a folder to zip file.
  220.    *
  221.    * @param string     $folder
  222.    *   Path to folder that should be zipped.
  223.    *
  224.    * @param ZipArchive $zipFile
  225.    *   Zipfile where files end up.
  226.    *
  227.    * @param int        $exclusiveLength
  228.    *   Number of text to be exclusived from the file path.
  229.    */
  230.   private static function folderToZip($folder, &$zipFile, $exclusiveLength) {
  231.     $handle = opendir($folder);
  232.  
  233.     while (FALSE !== $f = readdir($handle)) {
  234.       // Check for local/parent path or zipping file itself and skip.
  235.       if ($f != '.' && $f != '..' && $f != basename(__FILE__)) {
  236.         $filePath = "$folder/$f";
  237.         // Remove prefix from file path before add to zip.
  238.         $localPath = substr($filePath, $exclusiveLength);
  239.  
  240.         if (is_file($filePath)) {
  241.           $zipFile->addFile($filePath, $localPath);
  242.         }
  243.         elseif (is_dir($filePath)) {
  244.           // Add sub-directory.
  245.           $zipFile->addEmptyDir($localPath);
  246.           self::folderToZip($filePath, $zipFile, $exclusiveLength);
  247.         }
  248.       }
  249.     }
  250.     closedir($handle);
  251.   }
  252.  
  253.   /**
  254.    * Zip a folder (including itself).
  255.    * Usage:
  256.    *   Zipper::zipDir('path/to/sourceDir', 'path/to/out.zip');
  257.    *
  258.    * @param string $sourcePath
  259.    *   Relative path of directory to be zipped.
  260.    *
  261.    * @param string $outZipPath
  262.    *   Relative path of the resulting output zip file.
  263.    */
  264.   public static function zipDir($sourcePath, $outZipPath) {
  265.     $pathInfo = pathinfo($sourcePath);
  266.     $parentPath = $pathInfo['dirname'];
  267.     $dirName = $pathInfo['basename'];
  268.  
  269.     $z = new ZipArchive();
  270.     $z->open($outZipPath, ZipArchive::CREATE);
  271.     $z->addEmptyDir($dirName);
  272.     if ($sourcePath == $dirName) {
  273.       self::folderToZip($sourcePath, $z, 0);
  274.     }
  275.     else {
  276.       self::folderToZip($sourcePath, $z, strlen("$parentPath/"));
  277.     }
  278.     $z->close();
  279.  
  280.     $GLOBALS['status'] = array('success' => 'Successfully created archive ' . $outZipPath);
  281.   }
  282. }
  283. ?>
  284.  
  285. <!DOCTYPE html>
  286. <html>
  287. <head>
  288.   <title>File Unzipper + Zipper</title>
  289.   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  290.   <style type="text/css">
  291.     <!--
  292.     body {
  293.       font-family: Arial, sans-serif;
  294.       line-height: 150%;
  295.     }
  296.  
  297.     label {
  298.       display: block;
  299.       margin-top: 20px;
  300.     }
  301.  
  302.     fieldset {
  303.       border: 0;
  304.       background-color: #EEE;
  305.       margin: 10px 0 10px 0;
  306.     }
  307.  
  308.     .select {
  309.       padding: 5px;
  310.       font-size: 110%;
  311.     }
  312.  
  313.     .status {
  314.       margin: 0;
  315.       margin-bottom: 20px;
  316.       padding: 10px;
  317.       font-size: 80%;
  318.       background: #EEE;
  319.       border: 1px dotted #DDD;
  320.     }
  321.  
  322.     .status--ERROR {
  323.       background-color: red;
  324.       color: white;
  325.       font-size: 120%;
  326.     }
  327.  
  328.     .status--SUCCESS {
  329.       background-color: green;
  330.       font-weight: bold;
  331.       color: white;
  332.       font-size: 120%
  333.     }
  334.  
  335.     .small {
  336.       font-size: 0.7rem;
  337.       font-weight: normal;
  338.     }
  339.  
  340.     .version {
  341.       font-size: 80%;
  342.     }
  343.  
  344.     .form-field {
  345.       border: 1px solid #AAA;
  346.       padding: 8px;
  347.       width: 280px;
  348.     }
  349.  
  350.     .info {
  351.       margin-top: 0;
  352.       font-size: 80%;
  353.       color: #777;
  354.     }
  355.  
  356.     .submit {
  357.       background-color: #378de5;
  358.       border: 0;
  359.       color: #ffffff;
  360.       font-size: 15px;
  361.       padding: 10px 24px;
  362.       margin: 20px 0 20px 0;
  363.       text-decoration: none;
  364.     }
  365.  
  366.     .submit:hover {
  367.       background-color: #2c6db2;
  368.       cursor: pointer;
  369.     }
  370.     -->
  371.   </style>
  372. </head>
  373. <body>
  374. <p class="status status--<?php echo strtoupper(key($GLOBALS['status'])); ?>">
  375.   Status: <?php echo reset($GLOBALS['status']); ?><br/>
  376.   <span class="small">Processing Time: <?php echo $time; ?> seconds</span>
  377. </p>
  378. <form action="" method="POST">
  379.   <fieldset>
  380.     <h1>EBF Unzipper</h1>
  381.     <label for="zipfile">Select .zip or .rar archive or .gz file you want to extract:</label>
  382.     <select name="zipfile" size="1" class="select">
  383.       <?php foreach ($unzipper->zipfiles as $zip) {
  384.         echo "<option>$zip</option>";
  385.       }
  386.       ?>
  387.     </select>
  388.     <label for="extpath">Extraction path (optional):</label>
  389.     <input type="text" name="extpath" class="form-field" />
  390.     <p class="info">Enter extraction path without leading or trailing slashes (e.g. "mypath"). If left empty current directory will be used.</p>
  391.     <input type="submit" name="dounzip" class="submit" value="Unzip Archive"/>
  392.   </fieldset>
  393.  
  394.   <fieldset>
  395.     <h1>Archive Zipper</h1>
  396.     <label for="zippath">Path that should be zipped (optional):</label>
  397.     <input type="text" name="zippath" class="form-field" />
  398.     <p class="info">Enter path to be zipped without leading or trailing slashes (e.g. "zippath"). If left empty current directory will be used.</p>
  399.     <input type="submit" name="dozip" class="submit" value="Zip Archive"/>
  400.   </fieldset>
  401. </form>
  402. <p class="version">EBF Unzipper version: <?php echo VERSION; ?></p>
  403. </body>
  404. </html>
Advertisement
Add Comment
Please, Sign In to add comment