PHP如何在线解压压缩文件

简介: PHP如何在线解压压缩文档

php解压文件:php.png

<?php
/**
 * The Unzipper extracts .zip or .rar archives and .gz files on webservers.
 * It's handy if you do not have shell access. E.g. if you want to upload a lot
 * of files (php framework or image collection) as an archive to save time.
 * As of version 0.1.0 it also supports creating archives.
 *
 * @author  Andreas Tasch, at[tec], attec.at
 * @license GNU GPL v3
 * @package attec.toolbox
 * @version 0.1.1
 */
define('VERSION', '0.1.1');

$timestart = microtime(TRUE);
$GLOBALS['status'] = array();

$unzipper = new Unzipper;
if (isset($_POST['dounzip'])) {
   
   
  // Check if an archive was selected for unzipping.
  {
   
   mathJaxContainer[0]}_POST['zipfile']) ? strip_tags($_POST['zipfile']) : '';
  {
   
   mathJaxContainer[1]}_POST['extpath']) ? strip_tags($_POST['extpath']) : '';
  {
   
   mathJaxContainer[2]}archive, $destination);
}

if (isset($_POST['dozip'])) {
   
   
  {
   
   mathJaxContainer[3]}_POST['zippath']) ? strip_tags($_POST['zippath']) : '.';
  // Resulting zipfile e.g. zipper--2016-07-23--11-55.zip.
  $zipfile = 'zipper-' . date("Y-m-d--H-i") . '.zip';
  Zipper::zipDir({
   
   mathJaxContainer[4]}zipfile);
}

$timeend = microtime(TRUE);
{
   
   mathJaxContainer[5]}timeend - $timestart, 4);

/**
 * Class Unzipper
 */
class Unzipper {
   
   
  public $localdir = '.';
  public $zipfiles = array();

  public function __construct() {
   
   
    // Read directory and pick .zip, .rar and .gz files.
    if ({
   
   mathJaxContainer[6]}this->localdir)) {
   
   
      while (({
   
   mathJaxContainer[7]}dh)) !== FALSE) {
   
   
        if (pathinfo($file, PATHINFO_EXTENSION) === 'zip'
          || pathinfo($file, PATHINFO_EXTENSION) === 'gz'
          || pathinfo($file, PATHINFO_EXTENSION) === 'rar'
        ) {
   
   
          {
   
   mathJaxContainer[8]}file;
        }
      }
      closedir($dh);

      if (!empty($this->zipfiles)) {
   
   
        $GLOBALS['status'] = array('info' => '.zip or .gz or .rar files found, ready for extraction');
      }
      else {
   
   
        $GLOBALS['status'] = array('info' => 'No .zip or .gz or rar files found. So only zipping functionality available.');
      }
    }
  }

  /**
   * Prepare and check zipfile for extraction.
   *
   * @param string $archive
   *   The archive name including file extension. E.g. my_archive.zip.
   * @param string $destination
   *   The relative destination path where to extract files.
   */
  public function prepareExtraction({
   
   mathJaxContainer[9]}destination = '') {
   
   
    // Determine paths.
    if (empty($destination)) {
   
   
      {
   
   mathJaxContainer[10]}this->localdir;
    }
    else {
   
   
      {
   
   mathJaxContainer[11]}this->localdir . '/' . $destination;
      // Todo: move this to extraction function.
      if (!is_dir($extpath)) {
   
   
        mkdir($extpath);
      }
    }
    // Only local existing archives are allowed to be extracted.
    if (in_array({
   
   mathJaxContainer[12]}this->zipfiles)) {
   
   
      self::extract({
   
   mathJaxContainer[13]}extpath);
    }
  }

  /**
   * Checks file extension and calls suitable extractor functions.
   *
   * @param string $archive
   *   The archive name including file extension. E.g. my_archive.zip.
   * @param string $destination
   *   The relative destination path where to extract files.
   */
  public static function extract({
   
   mathJaxContainer[14]}destination) {
   
   
    {
   
   mathJaxContainer[15]}archive, PATHINFO_EXTENSION);
    switch ($ext) {
   
   
      case 'zip':
        self::extractZipArchive({
   
   mathJaxContainer[16]}destination);
        break;
      case 'gz':
        self::extractGzipFile({
   
   mathJaxContainer[17]}destination);
        break;
      case 'rar':
        self::extractRarArchive({
   
   mathJaxContainer[18]}destination);
        break;
    }

  }

  /**
   * Decompress/extract a zip archive using ZipArchive.
   *
   * @param $archive
   * @param $destination
   */
  public static function extractZipArchive({
   
   mathJaxContainer[19]}destination) {
   
   
    // Check if webserver supports unzipping.
    if (!class_exists('ZipArchive')) {
   
   
      $GLOBALS['status'] = array('error' => 'Error: Your PHP version does not support unzip functionality.');
      return;
    }

    $zip = new ZipArchive;

    // Check if archive is readable.
    if ({
   
   mathJaxContainer[20]}archive) === TRUE) {
   
   
      // Check if destination is writable
      if (is_writeable($destination . '/')) {
   
   
        {
   
   mathJaxContainer[21]}destination);
        $zip->close();
        $GLOBALS['status'] = array('success' => 'Files unzipped successfully');
      }
      else {
   
   
        $GLOBALS['status'] = array('error' => 'Error: Directory not writeable by webserver.');
      }
    }
    else {
   
   
      $GLOBALS['status'] = array('error' => 'Error: Cannot read .zip archive.');
    }
  }

  /**
   * Decompress a .gz File.
   *
   * @param string $archive
   *   The archive name including file extension. E.g. my_archive.zip.
   * @param string $destination
   *   The relative destination path where to extract files.
   */
  public static function extractGzipFile({
   
   mathJaxContainer[22]}destination) {
   
   
    // Check if zlib is enabled
    if (!function_exists('gzopen')) {
   
   
      $GLOBALS['status'] = array('error' => 'Error: Your PHP has no zlib support enabled.');
      return;
    }

    {
   
   mathJaxContainer[23]}archive, PATHINFO_FILENAME);
    {
   
   mathJaxContainer[24]}archive, "rb");
    {
   
   mathJaxContainer[25]}destination . '/' . $filename, "w");

    while ({
   
   mathJaxContainer[26]}gzipped, 4096)) {
   
   
      fwrite({
   
   mathJaxContainer[27]}string, strlen($string));
    }
    gzclose($gzipped);
    fclose($file);

    // Check if file was extracted.
    if (file_exists({
   
   mathJaxContainer[28]}filename)) {
   
   
      $GLOBALS['status'] = array('success' => 'File unzipped successfully.');

      // If we had a tar.gz file, let's extract that tar file.
      if (pathinfo({
   
   mathJaxContainer[29]}filename, PATHINFO_EXTENSION) == 'tar') {
   
   
        {
   
   mathJaxContainer[30]}destination . '/' . $filename);
        if ({
   
   mathJaxContainer[31]}destination)) {
   
   
          $GLOBALS['status'] = array('success' => 'Extracted tar.gz archive successfully.');
          // Delete .tar.
          unlink({
   
   mathJaxContainer[32]}filename);
        }
      }
    }
    else {
   
   
      $GLOBALS['status'] = array('error' => 'Error unzipping file.');
    }

  }

  /**
   * Decompress/extract a Rar archive using RarArchive.
   *
   * @param string $archive
   *   The archive name including file extension. E.g. my_archive.zip.
   * @param string $destination
   *   The relative destination path where to extract files.
   */
  public static function extractRarArchive({
   
   mathJaxContainer[33]}destination) {
   
   
    // Check if webserver supports unzipping.
    if (!class_exists('RarArchive')) {
   
   
      $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>');
      return;
    }
    // Check if archive is readable.
    if ({
   
   mathJaxContainer[34]}archive)) {
   
   
      // Check if destination is writable
      if (is_writeable($destination . '/')) {
   
   
        {
   
   mathJaxContainer[35]}rar->getEntries();
        foreach ({
   
   mathJaxContainer[36]}entry) {
   
   
          {
   
   mathJaxContainer[37]}destination);
        }
        $rar->close();
        $GLOBALS['status'] = array('success' => 'Files extracted successfully.');
      }
      else {
   
   
        $GLOBALS['status'] = array('error' => 'Error: Directory not writeable by webserver.');
      }
    }
    else {
   
   
      $GLOBALS['status'] = array('error' => 'Error: Cannot read .rar archive.');
    }
  }

}

/**
 * Class Zipper
 *
 * Copied and slightly modified from http://at2.php.net/manual/en/class.ziparchive.php#110719
 * @author umbalaconmeogia
 */
class Zipper {
   
   
  /**
   * Add files and sub-directories in a folder to zip file.
   *
   * @param string $folder
   *   Path to folder that should be zipped.
   *
   * @param ZipArchive $zipFile
   *   Zipfile where files end up.
   *
   * @param int $exclusiveLength
   *   Number of text to be exclusived from the file path.
   */
  private static function folderToZip({
   
   mathJaxContainer[38]}zipFile, $exclusiveLength) {
   
   
    {
   
   mathJaxContainer[39]}folder);

    while (FALSE !== {
   
   mathJaxContainer[40]}handle)) {
   
   
      // Check for local/parent path or zipping file itself and skip.
      if ({
   
   mathJaxContainer[41]}f != '..' && $f != basename(__FILE__)) {
   
   
        {
   
   mathJaxContainer[42]}folder/$f";
        // Remove prefix from file path before add to zip.
        {
   
   mathJaxContainer[43]}filePath, $exclusiveLength);

        if (is_file($filePath)) {
   
   
          {
   
   mathJaxContainer[44]}filePath, $localPath);
        }
        elseif (is_dir($filePath)) {
   
   
          // Add sub-directory.
          {
   
   mathJaxContainer[45]}localPath);
          self::folderToZip({
   
   mathJaxContainer[46]}zipFile, $exclusiveLength);
        }
      }
    }
    closedir($handle);
  }

  /**
   * Zip a folder (including itself).
   *
   * Usage:
   *   Zipper::zipDir('path/to/sourceDir', 'path/to/out.zip');
   *
   * @param string $sourcePath
   *   Relative path of directory to be zipped.
   *
   * @param string $outZipPath
   *   Relative path of the resulting output zip file.
   */
  public static function zipDir({
   
   mathJaxContainer[47]}outZipPath) {
   
   
    {
   
   mathJaxContainer[48]}sourcePath);
    {
   
   mathJaxContainer[49]}pathInfo['dirname'];
    {
   
   mathJaxContainer[50]}pathInfo['basename'];

    $z = new ZipArchive();
    {
   
   mathJaxContainer[51]}outZipPath, ZipArchive::CREATE);
    {
   
   mathJaxContainer[52]}dirName);
    if ({
   
   mathJaxContainer[53]}dirName) {
   
   
      self::folderToZip({
   
   mathJaxContainer[54]}z, 0);
    }
    else {
   
   
      self::folderToZip({
   
   mathJaxContainer[55]}z, strlen("$parentPath/"));
    }
    $z->close();

    {
   
   mathJaxContainer[56]}outZipPath);
  }
}
?>

<!DOCTYPE html>
<html>
<head>
  <title>File Unzipper + Zipper</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <style type="text/css">
    <!--
    body {
   
   
      font-family: Arial, sans-serif;
      line-height: 150%;
    }

    label {
   
   
      display: block;
      margin-top: 20px;
    }

    fieldset {
   
   
      border: 0;
      background-color: #EEE;
      margin: 10px 0 10px 0;
    }

    .select {
   
   
      padding: 5px;
      font-size: 110%;
    }

    .status {
   
   
      margin: 0;
      margin-bottom: 20px;
      padding: 10px;
      font-size: 80%;
      background: #EEE;
      border: 1px dotted #DDD;
    }

    .status--ERROR {
   
   
      background-color: red;
      color: white;
      font-size: 120%;
    }

    .status--SUCCESS {
   
   
      background-color: green;
      font-weight: bold;
      color: white;
      font-size: 120%
    }

    .small {
   
   
      font-size: 0.7rem;
      font-weight: normal;
    }

    .version {
   
   
      font-size: 80%;
    }

    .form-field {
   
   
      border: 1px solid #AAA;
      padding: 8px;
      width: 280px;
    }

    .info {
   
   
      margin-top: 0;
      font-size: 80%;
      color: #777;
    }

    .submit {
   
   
      background-color: #378de5;
      border: 0;
      color: #ffffff;
      font-size: 15px;
      padding: 10px 24px;
      margin: 20px 0 20px 0;
      text-decoration: none;
    }

    .submit:hover {
   
   
      background-color: #2c6db2;
      cursor: pointer;
    }
    -->
  </style>
</head>
<body>
<p class="status status--<?php echo strtoupper(key($GLOBALS['status'])); ?>">
  Status: <?php echo reset($GLOBALS['status']); ?><br/>
  <span class="small">Processing Time: <?php echo $time; ?> seconds</span>
</p>
<form action="" method="POST">
  <fieldset>
    <h1>Archive Unzipper</h1>
    <label for="zipfile">Select .zip or .rar archive or .gz file you want to extract:</label>
    <select name="zipfile" size="1" class="select">
      <?php foreach ({
   
   mathJaxContainer[57]}zip) {
   
   
        echo "<option>$zip</option>";
      }
      ?>
    </select>
    <label for="extpath">Extraction path (optional):</label>
    <input type="text" name="extpath" class="form-field" />
    <p class="info">Enter extraction path without leading or trailing slashes (e.g. "mypath"). If left empty current directory will be used.</p>
    <input type="submit" name="dounzip" class="submit" value="Unzip Archive"/>
  </fieldset>

  <fieldset>
    <h1>Archive Zipper</h1>
    <label for="zippath">Path that should be zipped (optional):</label>
    <input type="text" name="zippath" class="form-field" />
    <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>
    <input type="submit" name="dozip" class="submit" value="Zip Archive"/>
  </fieldset>
</form>
<p class="version">Unzipper version: <?php echo VERSION; ?></p>
</body>
</html>
相关文章
|
2月前
|
PHP
php常见问题,php.ini文件不存在或者找不到,mb_strlen()函数未定义系列问题,dll模块找不到的解决
本文介绍了解决PHP常见问题的步骤,包括定位和创建`php.ini`文件,以及解决`mb_strlen()`函数未定义和DLL模块加载错误的具体方法。
php常见问题,php.ini文件不存在或者找不到,mb_strlen()函数未定义系列问题,dll模块找不到的解决
|
5月前
|
存储 运维 Serverless
函数计算产品使用问题之在YAML文件中配置了环境变量,但在PHP代码中无法读取到这些环境变量,是什么原因
函数计算产品作为一种事件驱动的全托管计算服务,让用户能够专注于业务逻辑的编写,而无需关心底层服务器的管理与运维。你可以有效地利用函数计算产品来支撑各类应用场景,从简单的数据处理到复杂的业务逻辑,实现快速、高效、低成本的云上部署与运维。以下是一些关于使用函数计算产品的合集和要点,帮助你更好地理解和应用这一服务。
|
2月前
|
前端开发 PHP
php学习笔记-php文件表单上传-day06
本文介绍了PHP文件上传处理流程、预定义变量`$_FILES`的使用、文件上传状态代码以及文件上传实现函数。同时,通过一个文件上传的小例子,演示了文件上传表单的创建、文件上传表单处理的PHP页面编写以及运行测试输出。
php学习笔记-php文件表单上传-day06
|
2月前
|
缓存 监控 算法
分析慢日志文件来优化 PHP 脚本的性能
分析慢日志文件来优化 PHP 脚本的性能
|
2月前
进入靶场,出现一张照片,右击查看源代码,发现有一个注释的source.php文件
这段代码实现了一个网站上弹出的促销海报动画效果,包含一个关闭按钮。当促销海报弹出时,会在三秒后开始抖动一两下。海报使用固定定位居中显示,带有阴影和圆角,关闭按钮位于右上角。可以通过修改时间参数调整弹出时间。
17 0
|
3月前
|
存储 安全 数据库连接
php.ini 文件的用途是什么?
【8月更文挑战第29天】
59 1
|
3月前
|
PHP
PHP遍历文件并同步上传到服务器
在进行网站迁移时,由于原网站的图片文件过多,采用打包下载再上传的方式耗时过长,且尝试使用FTP工具从旧服务器传输至新服务器时失败。为解决此问题,特使用PHP编写了一款工具,该工具能扫描指定目录下的所有`.webp`图像文件,并将其上传至新的服务器,极大地提高了迁移效率。
98 16
|
3月前
|
Java 应用服务中间件 PHP
PHP——调用java文件中的方法
PHP——调用java文件中的方法
54 0
PHP——调用java文件中的方法
|
3月前
|
PHP
php怎么循环读取文件夹里的文件
`DirectoryIterator`类提供了一个接口来遍历文件系统目录。与 `glob`函数相比,使用 `DirectoryIterator`类可以获得更多文件属性信息,如文件大小、修改时间等,从而进行更复杂的文件处理操作。
36 0
|
4月前
|
API PHP UED
​一个PHP文件实现联系表单自动发送邮件
使用PHP和AOKSend服务,可以创建一个联系表单,收集用户信息并自动发送邮件。HTML表单包含姓名、邮箱和消息字段。PHP文件`send_mail.php`处理表单提交,通过AOKSend的SMTP设置(如主机、端口、API密钥)使用PHPMailer发送邮件到指定地址。代码中还包括安全措施,如使用`htmlspecialchars`防止XSS攻击。这种方法增强了网站的用户沟通体验,并依赖AOKSend的稳定性和API进行高效邮件发送。