将文件夹压缩成zip文件的php代码,寻觅目录文本内容的代码

By admin in 4858.com on 2019年7月28日

以此类能够用来搜寻在加以的文件目录中的文件。
它能够给定目录遍历递归查找有个别文件扩张名的文本。
并张开找到的公文,并检讨他们是还是不是带有寻找词语。

那是个可怜低价的先后,能够对文本文件实行一定的查找,并以特定的文字替换钦赐的文字,比如说只要本人那篇小说里有三个字全体打错了,有几十处,要每个寻找来修改是件很麻烦的事,用下边那些就足以轻巧化解。–teaman.oso.com.cn
类文件 search_replace.inc
<?php

前日要做叁个专程用来拍卖搜索文件的成效,而寻觅的公文或然是坐落有个别目录下的,搜索目录下是还是不是留存该目录,PHP函数当中好像从没特意这样的搜寻函数。

1.请先下载作者计划好的zip.php工具类,下载后解压,将里面包车型客车文本归入对应的目录中,笔者是放在虚构目录下的include文件夹中。
2.在你的php文件中投入上面代码就能够

它回到二个含有全部文件的列表富含搜索词语数组。

        class search_replace{

文件的操作在 php
中是不行缺点和失误的,而文件的使用功用也是可怜高的,例如大家广阔的目录管理种类,无数据库留言本等,都用到了文件的操作,而那边的文件指的不独有是目录的操作,还会有内定文件的操作,举例txt 文件等。

复制代码 代码如下:

复制代码 代码如下:

                var $find;
                var $replace;
                var $files;
                var $directories;
                var $include_subdir;
                var $ignore_lines;
                var $ignore_sep;
                var $occurences;
                var $search_function;
                var $last_error;

上面是二个特意用来文书找出的函数方法,file_search
是格局名,前边有多少个参数,$directory 是要研究的文本所在的目录,比方“admin/”目录下, $search 是寻找的文书了,$recursive
是判别是或不是找寻成功的,私下认可就足以了,若是还索要别的操作,可以在背后进行增添相应参数就可以。

require_once “./include/zip.php”;
$zip = new PHPZip();
//$zip -> createZip(“要压缩的文本夹目录地址”,
“压缩后的文件名.zip”);   //只生成不自动下载
$zip -> downloadZip(“要缩减的公文夹目录地址”,
“压缩后的文书名.zip”);  //自动下载

<?php
/*
Class for searching the contents of all the files in a directory and its
subdirectories
For support please visit
*/
class searchFileContents{
var $dir_name = ”;//The directory to search

        //以下举行函数定义和设置

例1

实例:能够参照下边包车型大巴伪代码来看贰个切实的选用情形:
代码

var $search_phrase = ”;//The phrase to search in the file contents
var $allowed_file_types = array(‘php’,’phps’);//The file types that
are searched
var $foundFiles;//Files that contain the search phrase will be stored
here
//开源代码OSPHP.COM.Cn
var $myfiles;
function search($directory, $search_phrase){
$this->dir_name = $directory;
$this->search_phrase = $search_phrase;

                function search_replace($find, $replace, $files,
$directories = ”, $include_subdir = 1, $ignore_lines = array()){

 代码如下

复制代码 代码如下:

$this->myfiles = $this->GetDirContents($this->dir_name);
$this->foundFiles = array();
if ( empty($this->search_phrase) ) die(‘Empty search phrase’);

                        $this->find            = $find;
                        $this->replace         = $replace;
                        $this->files           = $files;
                        $this->directories     = $directories;
                        $this->include_subdir  = $include_subdir;
                        $this->ignore_lines    = $ignore_lines;

<?php

require_once “./include/zip.php”;
if (!$download) {
exit();
}
set_time_limit(60);
$tmpManager = new TmpManager(); //假使大家有二个类来完毕前面包车型大巴操作
$tempfolder = array();
$tempfile = array();
//借使我们是经过在页面上选用checkbox来下载已选的公文夹或文件,并共同装进
for($i = 0;$i < $checkboxnum;$i++) {
$value = ${“select”.$i};
if ($value != ”) {
$this_type = substr($value, 0, 1);
$this_id = substr($value, 1);
//将文件夹和文书的图景分别管理
if ($this_type == ‘d’) {
$tempfolder[] = $this_id;
}
elseif ($this_type == ‘f’) {
$tempfile[] = $this_id;
}
}
}
@mkdir($tempdir);
$curtempdir = “$tempdir/”.$userid; //分化用户在分化的有的时候文件夹下操作
if (file_exists($curtempdir)) {
$tmpManager->DeleteDir($curtempdir); //删除旧的公文夹
}
if (sizeof($tempfolder) > 0 || sizeof($tempfile) > 0) {
mkdir($curtempdir, 0777); //假若有要打包的文书货文件夹,重新创制文件夹
}
if (sizeof($tempfile) > 0) {
$tmpManager->CopyFile($tempfile,$curtempdir);
//将要下载的文书copy到创制的文本夹
}
if (sizeof($tempfolder) > 0) {
$tmpManager->CopyFolder($tempfolder,$curtempdir);
//将在下载的文书夹copy到开创的文书夹
}
$zip = new PHPZip();
$zip -> downloadZip($curtempdir, “file_”.date(‘Ymd’).”.zip”);
//打包并下载

if ( empty($this->dir_name) ) die(‘You must select a directory to
search’);
foreach ( $this->myfiles as $f ){
if ( in_array(array_pop(explode ( ‘.’, $f )),
$this->allowed_file_types) ){ //开源OSPhP.COM.CN
$contents = file_get_contents($f);
if ( strpos($contents, $this->search_phrase) !== false )
$this->foundFiles [] = $f;
//开源代码OSPhP.COm.CN

                        $this->occurences      = 0;
                        $this->search_function = ‘search’;
                        $this->last_error      = ”;

function file_search($directory, $search, $recursive = TRUE)
{
$res = FALSE;
$dir_handle =
opendir($directory);
while( FALSE !== ($file = readdir($dir_handle)) )
{
if( $file == ‘.’ || $file == ‘..’ )
{
continue;
}
if( is_dir(“$directory\$file”) )
{
if( $recursive )
{
$res = file_search(“$directory\$file”, $search);
if( $res !== FALSE )
{
return $res;
}
}
}
if( $file == $search )
{
return “$directory\$file”;
}
}
return FALSE;
}
?>

zip.php

}
}
return $this->foundFiles;
}
function GetDirContents($dir){
if (!is_dir($dir)){die (“Function GetDirContents: Problem reading :
$dir!”);}
if ($root=@opendir($dir)){
//PHP开源代码

                }

例2

复制代码 代码如下:

while ($file=readdir($root)){
if($file==”.” || $file==”..”){continue;}
if(is_dir($dir.”/”.$file)){

        /***************************************
        ** Accessor for retrieving occurences.
        ***************************************/
                function get_num_occurences(){
                        return $this->occurences;
                }

 代码如下

<?php
/*
    File name: /include/zip.php
    Author:    Horace 2009/04/15
*/
class PHPZip{
    var $dirInfo = array(“0″,”0”);
    var $rootDir = ”;
    var $datasec = array();
    var $ctrl_dir = array();
    var $eof_ctrl_dir = “\x50\x4b\x05\x06\x00\x00\x00\x00”;
    var $old_offset = 0;

$files=array_merge($files,$this->GetDirContents($dir.”/”.$file));
}else{
$files[]=$dir.”/”.$file; //开源OSPhP.COM.CN
}
}
}
return $files;
}
}
//Example :
$search = new searchFileContents;
$search->search(‘E:/htdocs/AccessClass’, ‘class’);
//开源代码OSPHP.COM.Cn
var_dump($search->foundFiles);
?>

        //获取最终的失实
                function get_last_error(){
                        return $this->last_error;
                }

<?php
/*文本查找函数
用法:
findfile (目录,是还是不是遍历子目录,是还是不是查找文件内容,不查找的目录) ;
Ketle
2005-07-07
*/
function findfile ($dir, $find_sub_dir=false, $find_content=false,
$except_将文件夹压缩成zip文件的php代码,寻觅目录文本内容的代码。dir=false)
{
       
        $d = dir($dir);
        while (false !== ($entry = $d->read())) {
                if($entry == “.” || $entry == “..” || in_array ($entry,
$except_dir))
                        continue;
                $file = $d->path.”/”.$entry;
                if ( is_dir ( $file) )
                {
                        if ( $find_sub_dir )
                        {                               
                                findfile ($file, $find_sub_dir,
$find_content, $except_dir) ;
                        }
                       
                }else
                {
                        if ( $find_content )
                        {                               
                                if (
strstr(file_get_contents($file),$find_content) )
                                {
                                        echo $file.”<br>n”;
                                }
                        }else
                        {
                                echo $file.”<br>n”;
                        }
                               
                }   
        }
        $d->close();

    function downloadZip(){
        createZip($dir, $zipfilename, true);
    }
    function createZip($dir, $zipfilename, $autoDownload = false){
        if (@function_exists(‘gzcompress’)){
            @set_time_limit(“0”);
            if (is_array($dir)){
                $fd = fopen ($dir, “r”);
                $fileValue = fread ($fd, filesize ($filename));
                fclose ($fd);
                if (is_array($dir)) $filename = basename($dir);
                $this -> addFile($fileValue, “$filename”);
            }else{
                $this->dirTree($dir,$dir);
            }

        //设置FIND变量
                function set_find($find){
                        $this->find = $find;
                }

       
}

            $zipfilenametemp = time().$zipfilename;
            $out = $this -> filezip();
            $fp = fopen($zipfilenametemp, “w”);
            fwrite($fp, $out, strlen($out));
            fclose($fp);
            $filesize = filesize($zipfilenametemp);

        //设置replace变量
                function set_replace($replace){
                        $this->replace = $replace;
                }

//test:
findfile (‘..’,true,’芙蓉jj’,array(‘templates_c’,’admin’,’xixi’)) ;
?>

            if ($filesize < 104857600) {
                if($autoDownload){
                    header(“Content-type: application/octet-stream”);
                    header(“Content-disposition: attachment;
filename=”.$zipfilename);
                }
                echo $this -> filezip();
            }else{
                echo “create zip error!”;
            }
            unlink($zipfilenametemp);
        }
     }
    //get dir tree..
    function dirTree($directory,$rootDir){
        global $_SERVER,$dirInfo,$rootDir;

        //设置FILE变量
                function set_files($files){
                        $this->files = $files;
                }

例3

        $fileDir=$rootDir;
        $myDir=dir($directory);
        while($file=$myDir->read()){
            if(is_dir(“$directory/$file”) and $file!=”.” and
$file!=”..”){
                $dirInfo[0]++;
                $rootDir =”$fileDir$file/”;

        //设置目录变量
                function set_directories($directories){
                        $this->directories = $directories;
                }

使用php glob函数查找文件,遍历文件目录

                $this -> addFile(”, “$rootDir”);

        //设置目录变量 set_include_subdir
                function set_include_subdir($include_subdir){
                        $this->include_subdir = $include_subdir;
                }

函数表达:array glob ( string $pattern [, int $flags ] )
职能:找出与方式相称的文本路线,再次来到包括匹配文件(目录)的数组(注:被检查的文书必须是服务器系统的,不能够用来远程文件)
参数表明:第二个参数:相配方式;第1个可选参数:

                //go on n’s folders
                $this->dirTree(“$directory/$file”,$rootDir);
            }else{
                if($file!=”.” and $file!=”..”){
                    $dirInfo[1]++;
                    //$fd = fopen (“$directory/$file”, “r”);
                    $fileValue =
file_get_contents(“$directory/$file”);
                    //fclose ($fd);
                    $this -> addFile($fileValue, “$fileDir$file”);
                }
            }
        }
        $myDir->close();
    }
function unix2DosTime($unixtime = 0) {
$timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);

        //设置ignore_lines变量
                function set_ignore_lines($ignore_lines){
                        $this->ignore_lines = $ignore_lines;
                }

•GLOB_MASportageK – 在各类重回的品种中加八个斜线
•GLOB_NOSORT – 遵照文件在目录中冒出的本来顺序再次来到(不排序)
•GLOB_NOCHECK – 若无公文相配则赶回用于搜索的情势
•GLOB_NOESCAPE – 反斜线不转义元字符
•GLOB_BRACE – 扩充 {a,b,c} 来匹配 ‘a’,’b’ 或 ‘c’
•GLOB_ONLYDI奥迪Q7 – 仅重返与格局相称的目录项 

if ($timearray[‘year’] < 1980) {
     $timearray[‘year’] = 1980;
     $timearray[‘mon’] = 1;
     $timearray[‘mday’] = 1;
     $timearray[‘hours’] = 0;
     $timearray[‘minutes’] = 0;
     $timearray[‘seconds’] = 0;
} // end if

        //明确是哪种检索情势
                function set_search_function($search_function){
                        switch($search_function){
                                case ‘normal’:
$this->search_function = ‘search’;
                                               return TRUE;
                                               break;

 代码如下

return (($timearray[‘year’] – 1980) << 25) |
($timearray[‘mon’] << 21) | ($timearray[‘mday’] << 16)
|
($timearray[‘hours’] << 11) | ($timearray[‘minutes’] <<
5) | ($timearray[‘seconds’] >> 1);
}
function addFile($data, $name, $time = 0){
$name = str_replace(‘\\’, ‘/’, $name);

                                case ‘quick’ :
$this->search_function = ‘quick_search’;
                                               return TRUE;
                                               break;

$file = glob(‘{,.}*’, GLOB_BRACE); //相称全部文件
$file1 = glob(‘*.php’);  //相配全数php文件
print_r($file1);

$dtime = dechex($this->unix2DosTime($time));
$hexdtime = ‘\x’ . $dtime[6] . $dtime[7]
. ‘\x’ . $dtime[4] . $dtime[5]
. ‘\x’ . $dtime[2] . $dtime[3]
. ‘\x’ . $dtime[0] . $dtime[1];
eval(‘$hexdtime = “‘ . $hexdtime . ‘”;’);

                                case ‘preg’  :
$this->search_function = ‘preg_search’;
                                               return TRUE;
                                               break;

例4

$fr = “\x50\x4b\x03\x04”;
$fr .= “\x14\x00”; // ver needed to extract
$fr .= “\x00\x00”; // gen purpose bit flag
$fr .= “\x08\x00”; // compression method
$fr .= $hexdtime; // last mod time and date

                                case ‘ereg’  :
$this->search_function = ‘ereg_search’;
                                               return TRUE;
                                               break;

 代码如下

// “local file header” segment
$unc_len = strlen($data);
$crc = crc32($data);
$zdata = gzcompress($data);
$c_len = strlen($zdata);
$zdata = substr(substr($zdata, 0, strlen($zdata) – 4), 2); // fix crc
bug
$fr .= pack(‘V’, $crc); // crc32
$fr .= pack(‘V’, $c_len); // compressed filesize
$fr .= pack(‘V’, $unc_len); // uncompressed filesize
$fr .= pack(‘v’, strlen($name)); // length of filename
$fr .= pack(‘v’, 0); // extra field length
$fr .= $name;

                                default      :
$this->last_error      = ‘Invalid search function specified’;
                                               return FALSE;
                                               break;
                        }
                }

<?php

// “file data” segment
$fr .= $zdata;

        //以下为搜索和替换程序的主文件
                function search($filename){

print_r(listDir(‘./’)); //遍历当前目录
function listDir($dir){
    $dir .= substr($dir, -1) ==
‘/’ ? ” : ‘/’;
    $dirInfo = array();
    foreach (glob($dir.’*’)
as $v) {
        $dirInfo[] = $v;
        if(is_dir($v)){
            $dirInfo = array_merge($dirInfo, listDir($v));
        }
    }
    return $dirInfo;
}

// “data descriptor” segment (optional but necessary if archive is not
// served as file)
$fr .= pack(‘V’, $crc); // crc32
$fr .= pack(‘V’, $c_len); // compressed filesize
$fr .= pack(‘V’, $unc_len); // uncompressed filesize

                        $occurences = 0;
                        $file_array = file($filename);

// add this entry to array
$this -> datasec[] = $fr;
$new_offset = strlen(implode(”, $this->datasec));

                        for($i=0; $i<count($file_array); $i++){
                                $continue_flag = 0;
                                if(count($this->ignore_lines) >
0){
                                        for($j=0;
$j<count($this->ignore_lines); $j++){
                                                if(substr($file_array[$i],0,strlen($this->ignore_lines[$j]))
== $this->ignore_lines[$j]) $continue_flag = 1;
                                        }
                                }
                                if($continue_flag == 1) continue;
                                $occurences +=
count(explode($this->find, $file_array[$i])) – 1;
                                $file_array[$i] =
str_replace($this->find, $this->replace, $file_array[$i]);
                        }
                        if($occurences > 0) $return =
array($occurences, implode(”, $file_array)); else $return = FALSE;
                        return $return;

// now add to central directory record
$cdrec = “\x50\x4b\x01\x02”;
$cdrec .= “\x00\x00”; // version made by
$cdrec .= “\x14\x00”; // version needed to extract
$cdrec .= “\x00\x00”; // gen purpose bit flag
$cdrec .= “\x08\x00”; // compression method
$cdrec .= $hexdtime; // last mod time & date
$cdrec .= pack(‘V’, $crc); // crc32
$cdrec .= pack(‘V’, $c_len); // compressed filesize
$cdrec .= pack(‘V’, $unc_len); // uncompressed filesize
$cdrec .= pack(‘v’, strlen($name) ); // length of filename
$cdrec .= pack(‘v’, 0 ); // extra field length
$cdrec .= pack(‘v’, 0 ); // file comment length
$cdrec .= pack(‘v’, 0 ); // disk number start
$cdrec .= pack(‘v’, 0 ); // internal file attributes
$cdrec .= pack(‘V’, 32 ); // external file attributes – ‘archive’ bit
set

                }

$cdrec .= pack(‘V’, $this -> old_offset ); // relative offset of
local header
$this -> old_offset = $new_offset;

        //使用quick(急忙)搜索方法时,未有igonre_lines功能
                function quick_search($filename){

$cdrec .= $name;

                        clearstatcache();

// optional extra field, file comment goes here
// save to central directory
$this -> ctrl_dir[] = $cdrec;
}
function filezip(){
$data = implode(”, $this -> datasec);
$ctrldir = implode(”, $this -> ctrl_dir);

                        $file       = fread($fp = fopen($filename, ‘r’),
filesize($filename)); fclose($fp);
                        $occurences = count(explode($this->find,
$file)) – 1;
                        $file       = str_replace($this->find,
$this->replace, $file);

return
$data .
$ctrldir .
$this -> eof_ctrl_dir .
pack(‘v’, sizeof($this -> ctrl_dir)) . // total # of entries “on
this disk”
pack(‘v’, sizeof($this -> ctrl_dir)) . // total # of entries
overall
pack(‘V’, strlen($ctrldir)) . // size of central dir
pack(‘V’, strlen($data)) . // offset to start of central dir
“\x00\x00”; // .zip file comment length
}
}
?>

                        if($occurences > 0) $return =
array($occurences, $file); else $return = FALSE;
                        return $return;

zip.php文件打包

                }

您也许感兴趣的稿子:

  • PHP递归遍历文件夹去除注释并压缩php源代码的主意身体力行
  • PHP 压缩文件夹的类代码
  • php完结zip压缩文件解压缩代码分享(轻便易懂)
  • php生成zip压缩文件的秘籍详解
  • PHP Zip压缩
    在线对文件进行削减的函数
  • php启用zlib压缩文件的计划格局
  • PHP Zip解压
    文件在线解压缩的函数代码
  • php文件打包
    下载之使用PHP自带的ZipArchive压缩文件并下载打包好的文本
  • php压缩文件夹最新版

        //preg搜索方法不扶助ignore_lines
                function preg_search($filename){

                        clearstatcache();

                        $file       = fread($fp = fopen($filename, ‘r’),
filesize($filename)); fclose($fp);
                        $occurences = count($matches =
preg_split($this->find, $file)) – 1;
                        $file       = preg_replace($this->find,
$this->replace, $file);

                        if($occurences > 0) $return =
array($occurences, $file); else $return = FALSE;
                        return $return;

                }

        //ereg寻觅方法也不扶助ignore_lines
                function ereg_search($filename){

                        clearstatcache();

                        $file = fread($fp = fopen($filename, ‘r’),
filesize($filename)); fclose($fp);

                        $occurences = count($matches =
split($this->find, $file)) -1;
                        $file       = ereg_replace($this->find,
$this->replace, $file);

                        if($occurences > 0) $return =
array($occurences, $file); else $return = FALSE;
                        return $return;

                }

        //写新文件
                function writeout($filename, $contents){

                        if($fp = @fopen($filename, ‘w’)){
                                fwrite($fp, $contents);
                                fclose($fp);
                        }else{
                                $this->last_error = ‘Could not open
file: ‘.$filename;
                        }

                }

        //由do_search调用,排出全数要物色的文件
                function do_files($ser_func){
                        if(!is_array($this->files)) $this->files
= explode(‘,’, $this->files);
4858.com ,                        for($i=0; $i<count($this->files); $i++){
                                if($this->files[$i] == ‘.’ OR
$this->files[$i] == ‘..’) continue;
                                if(is_dir($this->files[$i]) ==
TRUE) continue;
                                $newfile =
$this->$ser_func($this->files[$i]);
                                if(is_array($newfile) == TRUE){
                                        $this->writeout($this->files[$i],
$newfile[1]);
                                        $this->occurences +=
$newfile[0];
                                }
                        }
                }

        //由do_search()调用,排出全体要探求的目录
                function do_directories($ser_func){
                        if(!is_array($this->directories))
$this->directories = explode(‘,’, $this->directories);
                        for($i=0; $i<count($this->directories);
$i++){
                                $dh =
opendir($this->directories[$i]);
                                while($file = readdir($dh)){
                                        if($file == ‘.’ OR $file ==
‘..’) continue;

                                        if(is_dir($this->directories[$i].$file)
== TRUE){
                                                if($this->include_subdir
== 1){
                                                        $this->directories[]
= $this->directories[$i].$file.’/’;
                                                        continue;
                                                }else{
                                                        continue;
                                                }
                                        }

                                        $newfile =
$this->$ser_func($this->directories[$i].$file);
                                        if(is_array($newfile) ==
TRUE){
                                                $this->writeout($this->directories[$i].$file,
$newfile[1]);
                                                $this->occurences +=
$newfile[0];
                                        }
                                }
                        }
                }

        //调用这一个do_search()就足以起来对文件或目录进行检索
                function do_search(){
                        if($this->find != ”){
                                if((is_array($this->files) AND
count($this->files) > 0) OR $this->files != ”)
$this->do_files($this->search_function);
                                if($this->directories !=
”)                                       $this->do_directories($this->search_function);
                        }
                }

        } // End of class
?>

//下面是调用该类的例子表达,请存为example.php

<?php

        include(‘search_replace.inc’);  //将文件包罗进去

//建构新物件,设置寻找条件、最终回到找寻结果

        $sr = new search_replace(‘asp’, ‘php’, array(‘test.txt’));
//调用找出与替换
        $sr->set_search_function(‘quick’);   //设置搜索条件
        $sr->do_search();

        $sr->set_find(‘another’);
        $sr->do_search();

//上边是定制的归来音讯
        header(‘Content-Type: text/plain’);
        echo ‘开采和替换以下多少个地点:
‘.$sr->get_num_occurences().”\r\n”;
        echo ‘啊,错误爆发如下………….:
‘.$sr->get_last_error().”\r\n”;
?>

//将以下文字存为test.txt,注意text.txt必须是可读可写的
“笔者万分喜欢asp,它大致命理术数,作用强,听别人说asp已经占了大半商城,asp真好。”

那时,假设您展开exampe.php 就能够现出上面这几个:
开采和替换以下多少个地点:3
嘿,错误产生如下……….:      
翻看test.txt文件,果然出现asp的地点被php替换了。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图
Copyright @ 2010-2019 美高梅手机版4858 版权所有