主要功能: ---文件的或者文件夹的copy ---文件或者文件夹的delete ---获取文件夹或者文件夹权限 --文件大小换算为大计量单位 ---遍历文件夹得到目录下文件夹二维数组

php对文件夹管理的一些函数代码



主要功能:

---文件的或者文件夹的copy

---文件或者文件夹的delete

---获取文件夹或者文件夹权限

--文件大小换算为大计量单位

---遍历文件夹得到目录下文件夹二维数组


<?php
/**
 * 文件操作模型
 */
class M_files {
 
    public $shearplate='';                                                          //剪切板
 
    /**
     * 构造函数
     */
    public function __construct() {
 
        !isset($_SESSION) && session_start();                                       //开启session
 
        $this->shearplate=$_SESSION['shearplate'];                                   //获取剪切板内容
 
        is_dir($_SESSION['chdir']) && chdir($_SESSION['chdir']);                    //当前目录
    }
    /**
     * 遍历目录
     * @access public
     * @param string dir
     * @return array 二维数组array(name=>array(size,mtime,type,power))
     */
    public function get($dir=''){
 
        $dirs=array();                                                              //目录文件数组
 
        $dir=is_dir($dir)?$this->set_path($dir):'.';
 
        $this->set_chdir($dir);                                                      //修改当前目录,确保路径正确
 
        if($handle=opendir($dir)){
 
            $cwd=$this->set_path(getcwd());                                          //当前工作目录
 
            while(false!==($file=readdir($handle))){                                //遍历目录
 
                if($file != "." ){//&& $file != ".."){                                  //去掉 . 和 ..
 
                    $file_arr=array(                                                //文件的详细信息
 
                                'size'          =>filesize($file),                   //文件大小
 
                                'mtime'     =>filemtime($file),                  //文件修改时间
 
                                'type'          =>$this->get_type($file),         //文件类型(目录-dir,文件:rar、jpg)
 
                                'power'     =>$this->get_power($file),            //文件权限
 
                                'path'          =>$this->set_path($cwd.$file)     //文件完整路径
                                    );
 
                    $dirs+=array($file=>$file_arr);                                  //得到二维文件信息数组
                }
            }
        }
 
        closedir($handle);                                                          //关闭目录
 
        return $dirs;
    }
 
    /**
     * 获取目录权限
     * @access public
     * @param string dir 目录
     * @return string power 权限
     */
    public function get_power($dir){
 
        $perms = fileperms($dir);
 
        if (($perms & 0xC000) == 0xC000) {
            // Socket
            $info = 's';
        } elseif (($perms & 0xA000) == 0xA000) {
            // Symbolic Link
            $info = 'l';
        } elseif (($perms & 0x8000) == 0x8000) {
            // Regular
            $info = '-';
        } elseif (($perms & 0x6000) == 0x6000) {
            // Block special
            $info = 'b';
        } elseif (($perms & 0x4000) == 0x4000) {
            // Directory
            $info = 'd';
        } elseif (($perms & 0x2000) == 0x2000) {
            // Character special
            $info = 'c';
        } elseif (($perms & 0x1000) == 0x1000) {
            // FIFO pipe
            $info = 'p';
        } else {
            // Unknown
            $info = 'u';
        }
 
        // Owner
        $info .= (($perms & 0x0100) ? 'r' : '-');
        $info .= (($perms & 0x0080) ? 'w' : '-');
        $info .= (($perms & 0x0040) ?
                    (($perms & 0x0800) ? 's' : 'x' ) :
                    (($perms & 0x0800) ? 'S' : '-'));
 
        // Group
        $info .= (($perms & 0x0020) ? 'r' : '-');
        $info .= (($perms & 0x0010) ? 'w' : '-');
        $info .= (($perms & 0x0008) ?
                    (($perms & 0x0400) ? 's' : 'x' ) :
                    (($perms & 0x0400) ? 'S' : '-'));
 
        // World
        $info .= (($perms & 0x0004) ? 'r' : '-');
        $info .= (($perms & 0x0002) ? 'w' : '-');
        $info .= (($perms & 0x0001) ?
                    (($perms & 0x0200) ? 't' : 'x' ) :
                    (($perms & 0x0200) ? 'T' : '-'));
 
        return $info;
    }
    /**
     * 获取文件类型
     * @access public
     * @param string file 文件
     * @return string type 文件类型
     */
    public function get_type($file){
 
        if(is_file($file)){
 
            $path=pathinfo($file);
 
            return $path['extension'];                  //获得后缀
        }
        else{
 
            return 'dir';                                   //目录返回dir
        }
    }
    /**
     * 复制文件或文件夹
     * @access public
     * @param string dir 目标(路径或重命名后的文件)
     * @param string files 当前文件,如果为空,调用剪贴板(/xx/xx.html|zz/xx/|xxx.htm)
     * @return bool true/false
     */
    public function copy_files($goal,$files=''){
 
        $falg=true;                                         //遇见错误将标记设置为false
 
        empty($files)?$files=$this->shearplate:$files;       //调用剪切板
 
        $path=$goal=$this->set_path($goal);                  //统一路径,并保存目标目录初始值
 
        $files=$this->set_path($files);                      //统一路径
 
        $file_arr=explode('|',trim($files,'|'));
 
        foreach($file_arr as  $file){                       //循环处理需要复制的文件
 
            $filename=basename($file);
 
            while(file_exists($goal.$filename)){            //得到新路径
 
                $filename='复件 '.$filename;              //确保同一文件复制多次正确
            }
 
            $goal=$goal.$filename;
 
            if(is_file($file)){
 
                $falg= @copy($file,$goal);                  //移动文件
            }
            else{
 
                $falg= @$this->copy_dir($file,$goal);        //移动目录
            }
 
            $goal=$path;                                    //重置路径,否则会命名出错
        }
 
        return $falg;
    }
    /**
     * 移动文件或文件夹
     * @access public
     * @param sting dir   目标(路径或重命名后的文件)
     * @param sting files 当前文件,如果为空,调用剪贴板(/xx/xx.html|zz/xx/|xxx.htm)
     * @return bool
     */
    public function move_files($goal,$files=''){
 
        $falg=true;                                         //遇见错误将标记设置为false
 
        !$this->copy_files($goal,$files) && $falg=false;                 //移动文件
 
        $falg && (!$this->del_files($files) && $falg=false);             //删除文件
 
        return $falg;
    }
    /**
     * 复制文件夹
     * @access public
     * @param string 复制文件夹
     * @param string 目标文件夹
     * @return bool ture/false
     */
    private  function copy_dir($source,$target){
 
       $source=rtrim($source,'/').'/';
 
       $target=rtrim($target,'/').'/';
 
       if(is_dir($source)){
 
            if(@!mkdir($target)){
 
             return false;
 
            }
 
            $d=dir($source);
 
            while(($entry=$d->read())!==false){
 
                 if(is_dir($source.$entry)){
 
                    if($entry=="."||$entry==".."){
                         continue;
                    }
                    else{
                        $this->copy_dir($source.$entry,$target.$entry);
                    }
                }
                else{
 
                    if(!copy($source.$entry,$target.$entry)){
 
                        return false;
                     }
                }
         }
       }
       else{
 
        if(@!copy($source,$target)){
 
            return false;
         }
       }
       return true;
      }
     /**
      * 删除文件或目录
      * @access public
      * @param sting files(/xxxx/xxxx|xxx.html)
      * @return bool true/false
      */
    public   function del_files($files){
 
        $falg=true;
 
        $files=$this->set_path($files);                      //统一路径
 
        $file_arr=explode('|',trim($files,'|'));
 
        foreach($file_arr as $key=>$file){                   //循环处理需要删除的文件
 
            if(is_file($file)){
 
                !unlink($file) && $falg=false;
 
            }
            elseif(is_dir($file)){                          //删除目录
 
                file_exists($this->get_chdir().$file) && $file=$this->get_chdir().$file;  //得到物理路径
 
                !$this->del_dir($file) && $falg=false;
            }
        }
 
        return $falg;
    }
    /**
     * 删除目录
     * @access private
     * @param string dir
     * @return bool
     */
    private function del_dir($dir){
 
        $dir=$this->set_path($dir);
 
        @$hand = opendir($dir);
 
        while(false!==($f = readdir($hand)))
        {
            if($f=='.'||$f=='..') continue;
 
            if(is_dir($dir.$f))
            {
                 $this->del_dir($dir.$f .'/');
            }
            else
            {
                 @unlink($dir . $f );
            }
        }
 
        @closedir($hand);                                   //关闭文件
 
        return @rmdir($dir);
    }
    /**
     * 换算文件大小
     * @access public
     * @param int bit
     * @return string
     */
    public function byte2big($size){
 
        $unit=1024;
 
        $mb=$size/($unit*$unit);
 
        $kb=$size/$unit;
 
        $bit=$size;
 
        ($bit>=1) && $str=$bit.'bit';
 
        ($kb>=1)  && $str=number_format($kb, 2, '.', '').'kb';
 
        ($mb>=1)  && $str=number_format($mb, 2, '.', '').'mb';
 
        return $str;
    }
 
     /**
      * 统一路径
      * @access public
      * @param string dir
      * @return string dir
      */
     public function set_path($dir){
 
            if(is_dir($dir) or substr($dir,-1)=='/'){           //目录
 
                return rtrim(strtr($dir,array('\\'=>'/')),'/').'/';
 
            }
            else{
 
                return strtr($dir,array('\\'=>'/'));
            }
     }
     /**
      * 修改当前目录
      * @access public
      * @param sting dir
      */
     public function set_chdir($dir){
 
        chdir($dir);
 
//      setcookie('chdir',$dir);                                //通过写入cookie保存当前目录
 
        $_SESSION['chdir']=$dir;                                //通过session保存当前目录
 
     }
 
     /**
      * 获取当前目录
      */
     public function get_chdir(){
 
        return $this->set_path(rtrim(getcwd(),'/').'/');
     }
 
     /**
      * 析构函数
      */
     public function __destruct(){
 
        $_SESSION['shearplate']=$this->shearplate;               //剪切板内容写入session以便跨页面使用
     }
}
?>


完成动作请求


<?php
 class Files extends Admin{
 
    private $mode=null;
 
    public function __construct(){
 
        parent::__construct();
 
        $this->mode=$this->LoadModel("M_files");          //加载文件管理模型
    }
 
    /**
     * 默认动作
     */
    public function index(){
 
        $this->show();
    }
    /**
     * 拷贝
     */
    public function fcopy(){
 
        if(!empty($_GET['f'])){
 
            $path=$this->mode->get_chdir();
 
            $shearplate_arr=explode('|',trim($_GET['f'],'|'));
 
            foreach($shearplate_arr as $file){
 
                empty($shearplate)? $shearplate=$path.$file:$shearplate=$shearplate.'|'.$path.$file;
            }
 
            $this->mode->shearplate=$shearplate;
        }
 
        $this->gotourl(-1);
    }
    /**
     * 剪切
     */
    public function fcut(){             //如果为剪切,剪切板最后加!
 
        if(!empty($_GET['f'])){
 
            $path=$this->mode->get_chdir();
 
            $shearplate_arr=explode('|',trim($_GET['f'],'|'));
 
            foreach($shearplate_arr as $file){
 
                empty($shearplate)? $shearplate=$path.$file:$shearplate=$shearplate.'|'.$path.$file;
            }
 
            $this->mode->shearplate=$shearplate.'!';
        }
 
        $this->gotourl(-1);
    }
    /**
     * 粘贴
     */
    public function fpaste(){
 
        $shearplate=$this->mode->shearplate;
 
        if(substr($shearplate,-1)=='!'){
 
            $shearplate=rtrim($shearplate,'!');
 
            $flag=true;
        }
 
        $goal=$this->mode->get_chdir();
 
        if($flag){
 
            $this->mode->move_files($goal,$shearplate)? $this->gotourl(-1):$error=true;  //剪切
        }
        else{
            $this->mode->copy_files($goal,$shearplate)? $this->gotourl(-1):$error=true;  //拷贝
        }
 
        if($error){
 
            $this->assign('title','操作错误');
 
            $this->assign('msg','操作失败<br><a href="#" onclick="history.go(-1)" >返回</a>');
 
            $this->display('msg.html');
        }
    }
   /**
    * 浏览文件夹
    */
   public function show(){
 
        ($_GET['dir']=='..:') && $_GET['dir']='';
 
        $_GET['dir']=strtr($_GET['dir'],array(':'=>'/'));
 
        $files=$this->mode->get(ROOT_PATH.'/'.$_GET['dir']);
 
        $top=ltrim(strtr($files['..']['path'],array('/'=>':')),ROOT_PATH);
 
        $top=$this->seturl("index.php/admin/files/show/dir/".strtr($top,array(' '=>'%20')),2);        //上级目录连接
 
        $files_str='<div class="webftp" id="webftp">';
 
        $files_str=$files_str."\r<div class=\"top\"><span class=\"ico\" style=\"".$this->get_ico('topdir')."\">" .
                "</span><span class=\"txt\"><a href=".$top.">".
                '上一层</a></span><span class="action">' .
                '<a title="创建文件夹" href="/admin/files/create/"  class="ico" style="'.$this->get_ico('newdir').'"></a>'.
                '<a title="创建文件" href="/admin/files/create/file/new"  class="ico" style="'.$this->get_ico('newfile').'"></a>'.
                '<a title="删除" href="#" onclick="webftp(\'del\')" class="ico" style="'.$this->get_ico('del').'"></a>' .
                '<a title="重命名" href="#" onclick="webftp(\'rn\');"  class="ico" style="'.$this->get_ico('edit').'"></a>' .
                '<a title="剪切" href="#" onclick="webftp(\'cut\');" class="ico" style="'.$this->get_ico('cut').'"></a>' .
                '<a title="复制" href="#" onclick="webftp(\'copy\');" class="ico" style="'.$this->get_ico('copy').'"></a>' .
                '<a title="粘贴" href="/admin/files/fpaste/" class="ico" style="'.$this->get_ico('paste').'"></a>' .
                "</span></div>\r<ul>";
 
        foreach($files as $key=>$value){                 //输出目录
 
            if($value['type']=='dir'){
 
                $link=ltrim(strtr($value['path'],array('/'=>':')),ROOT_PATH);
 
                $link=$this->seturl("index.php/admin/files/show/dir/".strtr($link,array(' '=>'%20')),2);
 
                if($key=='..'){
 
                }
                else{
                        $files_str=$files_str."\r<li><span class=\"ico\" style=\"".$this->get_ico($value['type'])."\">" .
                        "</span><a href=$link>".$key.'</a></li>';
                }
            }
        }
 
        foreach($files as $key=>$value){                 //输出文件
 
            if($value['type']!='dir'){
 
                $files_str=$files_str."\r<li><span class=\"ico\" style=\"".$this->get_ico($value['type'])."\"></span>".
                "<a href=#>".$key.'</a><span class="size">'.$this->mode->byte2big($value['size']).'</span></li>';
            }
        }
 
        $files_str=$files_str.'</ul></div>';
 
        $this->assign('msg',$files_str);
 
        $this->assign('title','webftp');
 
        $this->display('msg.html');
   }
   /**
    * 新建文件或者文件夹
    */
   public function create(){
 
    if(empty($_POST['newfile']) & empty($_POST['newdir'])){
 
        if(empty($_GET['file'])){
 
            $msg='创建文件夹:<form action="" method="post"><input  name="newdir" type="text" size="20"><br/>' .
                    '<input type="submit" value="创建文件夹"></form>';
        }
        else{
            $msg='创建文件:<form action="" method="post"><input  name="newfile" type="text" size="20"><br/>' .
                    '<input type="submit" value="创建文件"></form>';
        }
 
        $msg=$msg.'<br><a href="#" onclick="history.go(-1);">返回</a>';
 
        $this->assign('title','新建文件');
 
        $this->assign('msg',$msg);
 
        $this->display('msg.html');
    }
    else{//创建
 
        $path=$this->mode->get_chdir();
 
        if(!empty($_POST['newdir'])){
 
            $flag=mkdir($path.$_POST['newdir']);
        }
        else{
 
            $flag=fopen($path.$_POST['newfile'],'a');
 
            !$flag && fclose($flag);
        }
 
        $flag && $this->gotourl(-2);
    }
   }
   /**
    * 重命名文件夹或者文件
    */
   public function rn(){
 
        if(!empty($_POST['newname'])){
 
            $path=$this->mode->get_chdir();
 
            if(@rename($path.$_GET['f'],$path.$_POST['newname'])){
 
                $this->gotourl(-2);
            }
            else{
 
                $this->assign('title','重命名失败');
 
                $this->assign('msg','文件'.$_GET['f'].'命名失败!<br><a href="#" onclick="history.go(-1);">返回</a>');
 
                $this->display('msg.html');
            }
        }
        else{
 
            $this->assign('title','重命名文件');
 
            $this->assign('msg','将文件[<font color="red">'.$_GET['f'].'</font>]命名为:<form action=""  method="post">' .
                    '<input name="newname" tpye="text" size="20" />' .
                    '<br/><input type="submit" value="提交"></form><br><a href="#" onclick="history.go(-1);">返回</a>');
 
            $this->display('msg.html');
        }
   }
   /**
    * 删除文件
    */
   public function del(){
 
        if(!$_GET['f']==''){
 
            $flag=true;
 
            if($this->mode->del_files($_GET['f'])){
 
                    $this->gotourl(-1);
            }
            else{
 
                $this->assign('title','删除失败!');
 
                $this->assign('msg','文件'.$_GET['dir'].'删除失败!');
 
                $this->display('msg.html');
            }
        }
        else{
 
            $this->gotourl(-1);                                  //没有删除对象,返回
        }
   }
   /**
    * 输出style
    */
   private function set_ico($abc,$num){
 
        $witht=16;                              //块宽
 
        $height=16;                             //块高
 
        $num_arr=range(1,26);
 
        $abc_arr=range(a,z);
 
        $abc_arr=array_combine($abc_arr,$num_arr);  //a=>1,b=>2
 
        return "background-position:-".$abc_arr[$abc]*$witht."px -".$num*$height."px;";
   }
   /**
    * ico 映射
    */
   private function get_ico($type){
 
        $icos=array('default'       =>   'e,4',
 
                    'txt'           =>  'h,6',       //文本文件
 
                    'php'           =>  'a,3',       //php文件
 
                    'gz'            =>   'a,3',      //gz压缩格式
 
                    'dir'           =>  'b,1',       //文件夹
 
                    'del'           =>  'm,2',       //删除
 
                    'edit'          =>  'q,7',       //编辑
 
                    'cut'           =>  'j,2',       //剪切
 
                    'copy'          =>   'a,4',      //复制
 
                    'paste'     =>   'b,5',      //粘贴
 
                    'newdir'        =>   'h,1',      //新建文件夹
 
                    'topdir'        =>   'n,6',      //上级目录
 
                    'newfile'       =>   'c,4'       //新建文件
                    );
 
        empty($icos[$type])?$ico=$icos['default']:$ico=$icos[$type];
 
        $str=explode(',',$ico);
 
        $abc=$str[0]; $num=$str[1];
 
        return $this->set_ico($abc,$num);
   }
 }


上一篇:使用SSL在IIS中配置HTTPS网站

下一篇:完整php代码使用smtp类发送电子邮件

评论列表
发表评论
称呼
邮箱
网址
验证码(*)
热评文章
相关阅读