首頁 > 後端開發 > php教程 > php在線壓縮zip檔的方法

php在線壓縮zip檔的方法

墨辰丷
發布: 2023-03-29 19:04:01
原創
2425 人瀏覽過

本篇文章主要介绍php在线压缩zip文件的方法,感兴趣的朋友参考下,希望对大家有所帮助。

代码如下:

<?php
//在URL后参加 ?pwd=密码 查看生成密码
$password = &#39;8baa717e6265d1c1d762cc896151f821&#39;; //l23
?>
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>php ZIP压缩程序</title>
<style type="text/css">
<!--
html{background:#f9f9f9;}body{background:#fff;color:#333;font-family:sans-serif;margin:2em auto;width:700px;padding:1em 2em;-moz-border-radius:11px;-khtml-border-radius:11px;-webkit-border-radius:11px;border-radius:11px;border:1px solid #dfdfdf;}a{color:#2583ad;text-decoration:none;}a:hover{color:#d54e21;}h1{border-bottom:1px solid #dadada;clear:both;color:#666;font:24px Georgia,"Times New Roman",Times,serif;margin:5px 0 0 -4px;padding:0;padding-bottom:7px;}h2{font-size:16px;}p,li,dd,dt{padding-bottom:2px;font-size:12px;line-height:18px;}code,.code{font-size:13px;}ul,ol,dl{padding:5px 5px 5px 22px;}a img{border:0;}abbr{border:0;font-variant:normal;}#logo{margin:6px 0 14px 0;border-bottom:none;text-align:center;}.step{margin:20px 0 15px;}.step,th{text-align:left;padding:0;}.submit input,.button,.button-secondary{font-family:sans-serif;text-decoration:none;font-size:14px!important;line-height:16px;padding:6px 12px;cursor:pointer;border:1px solid #bbb;color:#464646;-moz-border-radius:15px;-khtml-border-radius:15px;-webkit-border-radius:15px;border-radius:15px;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;-khtml-box-sizing:content-box;box-sizing:content-box;}.button:hover,.button-secondary:hover,.submit input:hover{color:#000;border-color:#666;}textarea{border:1px solid #bbb;-moz-border-radius:3px;-khtml-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;}.form-table{border-collapse:collapse;margin-top:1em;width:100%;}.form-table td{margin-bottom:9px;padding:10px;border-bottom:8px solid #fff;font-size:12px;}.form-table th{font-size:13px;text-align:left;padding:16px 10px 10px 10px;border-bottom:8px solid #fff;width:130px;vertical-align:top;}.form-table tr{background:#f3f3f3;}.form-table code{line-height:18px;font-size:18px;}.form-table p{margin:4px 0 0 0;font-size:11px;}.form-table input{line-height:20px;font-size:15px;padding:2px;}.form-table th p{font-weight:normal;}#error-page{margin-top:50px;}#error-page p{font-size:12px;line-height:18px;margin:25px 0 20px;}#error-page code,.code{font-family:Consolas,Monaco,monospace;}#pass-strength-result{background-color:#eee;border-color:#ddd!important;border-style:solid;border-width:1px;margin:5px 5px 5px 1px;padding:5px;text-align:center;width:200px;display:none;}#pass-strength-result.bad{background-color:#ffb78c;border-color:#ff853c!important;}#pass-strength-result.good{background-color:#ffec8b;border-color:#fc0!important;}#pass-strength-result.short{background-color:#ffa0a0;border-color:#f04040!important;}#pass-strength-result.strong{background-color:#c3ff88;border-color:#8dff1c!important;}.message{border:1px solid #e6db55;padding:.3em .6em;margin:5px 0 15px;background-color:#ffffe0;}
.mydirname {color:#F00;}
.myfilename {color:#649ABE;}
.currentdir {font-size:14px;font-family: Georgia, Consolas;font-weight:bold;}
#footer {text-align:center;margin-top:20px;}
-->
</style>
</head>
 
<body>
 <form name="myform" id="myform" method="post" action="<?php echo $_SERVER[&#39;PHP_SELF&#39;];?>">
<h1 style="color:#2583ad;">在线压缩ZIP文件程序</h1><br>
 
<p>
   <p>使用方法:选定要压缩的文件或目录(包含子目录),即可开始压缩。压缩的结果保留原来的目录结构。<br />
   <?php if(isset($_REQUEST[&#39;pwd&#39;]) && md5($_REQUEST[&#39;pwd&#39;]) == $password)
   echo &#39;当前目录:<span>&#39;. dirname(__FILE__) . &#39;</span>        <a href="&#39;.
   $_SERVER[&#39;PHP_SELF&#39;]. &#39;">退出</a>&#39;;
     else
      if(isset($_GET[&#39;pwd&#39;]) )
        echo &#39;密码值:<span>&#39;. md5($_GET[&#39;pwd&#39;]) . &#39;</span>&#39;;
      else
        echo &#39;Tips:在URL后参加<span>?pwd=密码</span> 查看生成密码.&#39;;
    ?>
   </p>
</p>
<?
if(!isset($_REQUEST["myaction"])):
?>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
   <td width="11%">验证密码: </td>
   <td width="89%"><input name="pwd" type="password" id="password" size="30" onkeydown="if(event.ctrlKey&&event.keyCode==13){document.getElementById(&#39;login&#39;).click();return false};"></td>
  </tr>
  <tr>
   <td><input name="myaction" type="hidden" id="myaction" value="dolist"></td>
   <td><input type="submit" name="Submit" id="login" value=" 进 入 "></td>
  </tr>
 </table>
 <script type="text/javascript">
 document.getElementById(&#39;password&#39;).focus();
 </script>
<?
 
elseif($_REQUEST["myaction"]=="dolist"):
 
  if(!isset($_REQUEST[&#39;pwd&#39;]) || empty($_REQUEST[&#39;pwd&#39;]) )
    die(&#39;请输入密码! <a href="&#39;. $_SERVER[&#39;PHP_SELF&#39;]. &#39;">Again</a>&#39;);
  if(md5($_REQUEST[&#39;pwd&#39;]) != $password)
    die(&#39;输入的密码不正确!<a href="&#39;. $_SERVER[&#39;PHP_SELF&#39;]. &#39;">Again</a>&#39;);
echo &#39;选择要排除的目录(相对路径,以英文半角逗号分隔):<br />&#39;;
echo &#39;<input type="text" id="toexlude" name="toexlude" size="100" /><br />&#39;;
  echo "选择要压缩的文件或目录:<br/>";
   $fdir = opendir(&#39;./&#39;);
  while($file=readdir($fdir)){
    if($file==&#39;.&#39;|| $file==&#39;..&#39; ) continue;
    echo "<input name=&#39;dfile[]&#39; type=&#39;checkbox&#39; value=&#39;$file&#39; ".($file==basename(__FILE__)?"":"checked")."> ";
    if(is_file($file)){
      echo "<span>文件: $file</span><br>";
    }else{
      echo "<span>目录: $file</span><br>";
    }
  }
?>
<br>
压缩文件保存到目录:
<input name="todir" type="text" id="todir" value="_zipfiles<?php echo substr(md5(time()),0,8);?>_" size="20">
(留空为本目录,必须有写入权限)<br>
压缩文件名称:
<input name="zipname" type="text" id="zipname" value="backup_<?php echo substr(md5(__FILE__),0,8);?>.zip" size="15">
(.zip)<br>
<br>
<input name="pwd" type="hidden" id="password" value="<?php echo $_POST[&#39;pwd&#39;];?>">
<input name="myaction" type="hidden" id="myaction" value="dozip">
<input type=&#39;button&#39; value=&#39;反选&#39; onclick=&#39;selrev();&#39;>
<input type="submit" name="Submit" value=" 开始压缩 ">
<script language=&#39;javascript&#39;>
function selrev() {
  with(document.getElementById(&#39;myform&#39;)){
    for(i=0;i<elements.length;i++) {
      thiselm = elements[i];
      if(thiselm.name.match(/dfile\[]/))  thiselm.checked = !thiselm.checked;
    }
  }
}
</script>
<?
 
elseif($_REQUEST["myaction"]=="dozip"):
 
// set_time_limit(0);
 
 class PHPzip{
 
  var $file_count = 0 ;
  var $datastr_len  = 0;
  var $dirstr_len = 0;
  var $filedata = &#39;&#39;; //该变量只被类外部程序访问
  var $gzfilename;
  var $fp;
  var $dirstr=&#39;&#39;;
  /*
  返回文件的修改时间格式.
  只为本类内部函数调用.
  */
  function unix2DosTime($unixtime = 0) {
    $timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);
 
    if ($timearray[&#39;year&#39;] < 1980) {
      $timearray[&#39;year&#39;]  = 1980;
      $timearray[&#39;mon&#39;]   = 1;
      $timearray[&#39;mday&#39;]  = 1;
      $timearray[&#39;hours&#39;]  = 0;
      $timearray[&#39;minutes&#39;] = 0;
      $timearray[&#39;seconds&#39;] = 0;
    }
 
    return (($timearray[&#39;year&#39;] - 1980) << 25) | ($timearray[&#39;mon&#39;] << 21) | ($timearray[&#39;mday&#39;] << 16) |
        ($timearray[&#39;hours&#39;] << 11) | ($timearray[&#39;minutes&#39;] << 5) | ($timearray[&#39;seconds&#39;] >> 1);
  }
 
  /*
  初始化文件,建立文件目录,
  并返回文件的写入权限.
  */
  function startfile($path = &#39;myzip.zip&#39;){
    $this->gzfilename=$path;
    $mypathdir=array();
    do{
      $mypathdir[] = $path = dirname($path);
    }while($path != &#39;.&#39;);
    @end($mypathdir);
    do{
      $path = @current($mypathdir);
      @mkdir($path);
    }while(@prev($mypathdir));
 
    if($this->fp=@fopen($this->gzfilename,"w")){
      return true;
    }
    return false;
  }
 
  /*
  添加一个文件到 zip 压缩包中.
  */
  function addfile($data, $name){
    $name   = str_replace(&#39;\\&#39;, &#39;/&#39;, $name);
 
    if(strrchr($name,&#39;/&#39;)==&#39;/&#39;) return $this->adddir($name);
 
    $dtime  = dechex($this->unix2DosTime());
    $hexdtime = &#39;\x&#39; . $dtime[6] . $dtime[7]
         . &#39;\x&#39; . $dtime[4] . $dtime[5]
         . &#39;\x&#39; . $dtime[2] . $dtime[3]
         . &#39;\x&#39; . $dtime[0] . $dtime[1];
    eval(&#39;$hexdtime = "&#39; . $hexdtime . &#39;";&#39;);
 
    $unc_len = strlen($data);
    $crc   = crc32($data);
    $zdata  = gzcompress($data);
    $c_len  = strlen($zdata);
    $zdata  = substr(substr($zdata, 0, strlen($zdata) - 4), 2);
 
    //新添文件内容格式化:
    $datastr = "\x50\x4b\x03\x04";
    $datastr .= "\x14\x00";      // ver needed to extract
    $datastr .= "\x00\x00";      // gen purpose bit flag
    $datastr .= "\x08\x00";      // compression method
    $datastr .= $hexdtime;       // last mod time and date
    $datastr .= pack(&#39;V&#39;, $crc);       // crc32
    $datastr .= pack(&#39;V&#39;, $c_len);      // compressed filesize
    $datastr .= pack(&#39;V&#39;, $unc_len);     // uncompressed filesize
    $datastr .= pack(&#39;v&#39;, strlen($name));  // length of filename
    $datastr .= pack(&#39;v&#39;, 0);        // extra field length
    $datastr .= $name;
    $datastr .= $zdata;
    $datastr .= pack(&#39;V&#39;, $crc);         // crc32
    $datastr .= pack(&#39;V&#39;, $c_len);        // compressed filesize
    $datastr .= pack(&#39;V&#39;, $unc_len);       // uncompressed filesize
 
 
    fwrite($this->fp,$datastr);  //写入新的文件内容
    $my_datastr_len = strlen($datastr);
    unset($datastr);
 
    //新添文件目录信息
    $dirstr = "\x50\x4b\x01\x02";
    $dirstr .= "\x00\x00";          // version made by
    $dirstr .= "\x14\x00";          // version needed to extract
    $dirstr .= "\x00\x00";          // gen purpose bit flag
    $dirstr .= "\x08\x00";          // compression method
    $dirstr .= $hexdtime;           // last mod time & date
    $dirstr .= pack(&#39;V&#39;, $crc);        // crc32
    $dirstr .= pack(&#39;V&#39;, $c_len);       // compressed filesize
    $dirstr .= pack(&#39;V&#39;, $unc_len);      // uncompressed filesize
    $dirstr .= pack(&#39;v&#39;, strlen($name) );   // length of filename
    $dirstr .= pack(&#39;v&#39;, 0 );         // extra field length
    $dirstr .= pack(&#39;v&#39;, 0 );         // file comment length
    $dirstr .= pack(&#39;v&#39;, 0 );         // disk number start
    $dirstr .= pack(&#39;v&#39;, 0 );         // internal file attributes
    $dirstr .= pack(&#39;V&#39;, 32 );        // external file attributes - &#39;archive&#39; bit set
    $dirstr .= pack(&#39;V&#39;,$this->datastr_len ); // relative offset of local header
    $dirstr .= $name;
 
    $this->dirstr .= $dirstr;  //目录信息
 
    $this -> file_count ++;
    $this -> dirstr_len += strlen($dirstr);
    $this -> datastr_len += $my_datastr_len;
  }
 
  function adddir($name){
    $name = str_replace("\\", "/", $name);
    $datastr = "\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00";
 
    $datastr .= pack("V",0).pack("V",0).pack("V",0).pack("v", strlen($name) );
    $datastr .= pack("v", 0 ).$name.pack("V", 0).pack("V", 0).pack("V", 0);
 
    fwrite($this->fp,$datastr);  //写入新的文件内容
    $my_datastr_len = strlen($datastr);
    unset($datastr);
 
    $dirstr = "\x50\x4b\x01\x02\x00\x00\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00";
    $dirstr .= pack("V",0).pack("V",0).pack("V",0).pack("v", strlen($name) );
    $dirstr .= pack("v", 0 ).pack("v", 0 ).pack("v", 0 ).pack("v", 0 );
    $dirstr .= pack("V", 16 ).pack("V",$this->datastr_len).$name;
 
    $this->dirstr .= $dirstr;  //目录信息
 
    $this -> file_count ++;
    $this -> dirstr_len += strlen($dirstr);
    $this -> datastr_len += $my_datastr_len;
  }
 
 
  function createfile(){
    //压缩包结束信息,包括文件总数,目录信息读取指针位置等信息
    $endstr = "\x50\x4b\x05\x06\x00\x00\x00\x00" .
          pack(&#39;v&#39;, $this -> file_count) .
          pack(&#39;v&#39;, $this -> file_count) .
          pack(&#39;V&#39;, $this -> dirstr_len) .
          pack(&#39;V&#39;, $this -> datastr_len) .
          "\x00\x00";
 
    fwrite($this->fp,$this->dirstr.$endstr);
    fclose($this->fp);
  }
 }
 
 
  if(!trim($_REQUEST[&#39;zipname&#39;]))
    $_REQUEST[&#39;zipname&#39;] = &#39;backup_&#39;.substr(md5(__FILE__),0,8). &#39;.zip&#39;;
  else
    $_REQUEST[&#39;zipname&#39;] = trim($_REQUEST[&#39;zipname&#39;]);
  if(!strrchr(strtolower($_REQUEST[&#39;zipname&#39;]),&#39;.&#39;)==&#39;.zip&#39;)
    $_REQUEST[&#39;zipname&#39;] .= ".zip";
  $_REQUEST[&#39;todir&#39;] = str_replace(&#39;\\&#39;,&#39;/&#39;,trim($_REQUEST[&#39;todir&#39;]));
  if(!strrchr(strtolower($_REQUEST[&#39;todir&#39;]),&#39;/&#39;)==&#39;/&#39;)
    $_REQUEST[&#39;todir&#39;] .= "/";
  if($_REQUEST[&#39;todir&#39;]=="/")
    $_REQUEST[&#39;todir&#39;] = "./";
 
  function listfiles($dir="."){
    global $faisunZIP;
    $sub_file_num = 0;
 
    if(is_file($dir)){
     if(realpath($faisunZIP->gzfilename)!=realpath($dir)){
      $faisunZIP -> addfile(implode(&#39;&#39;,file($dir)),$dir);
      return 1;
     }
      return 0;
    }
 
    $handle=opendir($dir);
    //添加排除
    $to_exlude = !empty($_POST[&#39;toexlude&#39;]) ? $_POST[&#39;toexlude&#39;] :&#39;&#39;;
    $exlude = empty($to_exlude) ? array() : explode(&#39;,&#39;,$to_exlude);
    while ($file = readdir($handle)) {
      if($file=="."||$file==".." || $file == &#39;wp-content&#39; )continue;
      if(is_dir("$dir/$file") && !in_array("$dir/$file",$exlude) )
      {
       $sub_file_num += listfiles("$dir/$file");
      }
      else {
         if(realpath($faisunZIP ->gzfilename)!=realpath("$dir/$file")){
         $faisunZIP -> addfile(implode(&#39;&#39;,file("$dir/$file")),"$dir/$file");
         $sub_file_num ++;
        }
      }
    }
    closedir($handle);
    if(!$sub_file_num) $faisunZIP -> addfile("","$dir/");
    return $sub_file_num;
  }
 
  function num_bitunit($num){
   $bitunit=array(&#39; B&#39;,&#39; KB&#39;,&#39; MB&#39;,&#39; GB&#39;);
   for($key=0;$key<count($bitunit);$key++){
    if($num>=pow(2,10*$key)-1){ //1023B 会显示为 1KB
     $num_bitunit_str=(ceil($num/pow(2,10*$key)*100)/100)." $bitunit[$key]";
    }
   }
   return $num_bitunit_str;
  }
 
  if(is_array($_REQUEST[&#39;dfile&#39;])){
    $faisunZIP = new PHPzip;
    if($faisunZIP -> startfile($_REQUEST[&#39;todir&#39;].$_REQUEST[&#39;zipname&#39;])){
      echo "正在添加压缩文件...<br><br>";
      $filenum = 0;
      foreach($_REQUEST[&#39;dfile&#39;] as $file){
        if(is_file($file)){
          echo "<span>文件: $file </span><br>";
        }else{
          echo "<span>目录: $file </span><br>";
        }
        $filenum += listfiles($file);
      }
      $faisunZIP -> createfile();
      echo "<br>压缩完成,共添加 $filenum 个文件.<br /><a href=&#39;" .$_REQUEST[&#39;todir&#39;].$_REQUEST[&#39;zipname&#39;]. "&#39;>". $_REQUEST[&#39;todir&#39;].$_REQUEST[&#39;zipname&#39;]." (".num_bitunit(filesize("$_REQUEST[todir]$_REQUEST[zipname]")).")</a>";
    }else{
      echo $_REQUEST[&#39;todir&#39;].$_REQUEST[&#39;zipname&#39;].&#39;不能写入,请检查路径或权限是否正确.<br>&#39;;
    }
  }else{
    echo "没有选择的文件或目录.<br>";
  }
 
 
endif;
 
?>
 </form>
 <p id="footer">
 <p> <a href="javascript:;" onclick="scrollTo(0,0);" title="返回顶部">TOP</a></p>
 </p>
</body>
</html>
登入後複製

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。

相关推荐:

php使用ffmpeg实现向视频中添加文字字幕的方法

php 数组随机取值的方法及简单实例

php parse_str() 函数的定义与用法实例详解

以上是php在線壓縮zip檔的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板