PHP对文件的操作

阅读量:3700

发布时间:2015-10-27 22:54:04


一、说明

主要是通过Web页面对后台的文件、目录的一些相关操作,能实现和在Windows对文件的相关操作,为了不需要通过Linux命令就可以管理后台的资源文件。

 

二、需要的操作

编号 操作 文件 目录
1 创建文件/目录 1 1
2 判断文件/目录的权限 1 1
3 判断文件/目录大小 1 1
4 文件/目录的创建时间、修改时间、访问时间 1 1
5 查看文件/目录内容 1 1
6 文件/目录删除 1 1
7 文件/目录重命名 1 1
8 文件/目录拷贝 1 1
9 文件/目录剪切 1 1
10 文件/目录的下载 1 1
11 上传 1  
12 文件修改内容 1  

 

三、相关函数

函数 说明 使用
basename 返回路径中的文件名部分 string basename ( string $path [, string $suffix ] )
chmod 改变文件模式 bool chmod ( string $filename , int $mode )
clearstatcache 清除文件转态缓存 void clearstatcache ([ bool $clear_realpath_cache = false [, string $filename ]] )
copy 拷贝文件 bool copy ( string $source , string $dest [, resource $context ] )
dirname 返回路径中的目录部分 string dirname ( string $path )
fclose 关闭一个已打开的文件指针

bool fclose ( resource $handle )文件指针必须有效,并且是通过 fopen() 或 fsockopen() 成功打开的。 

fgetc 从文件指针中读取字符串 string fgetc ( resource $handle )
fgets 从文件指针中读取一行 string fgets ( resource $handle [, int $length ] )
file_exists 检查文件或目录是否存在 bool file_exists ( string $filename )
file_get_contents 将整个文件读入一个字符串 string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )
file_put_contents 将个字符串写入文件 int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )
file 把文件读入一个数组中 array file ( string $filename [, int $flags = 0 [, resource $context ]] )
fileatime 取得文件上次访问时间 int fileatime ( string $filename )
filectime 文件的创建时间 int filectime ( string $filename )
filemtime 文件的修改时间 int filemtime ( string $filename )
fileperms 取得文件的权限 int fileperms ( string $filename )
filesize 文件的大小 int filesize ( string $filename )
filetype 取得文件的类型 string filetype ( string $filename )
fread 读取文件 string fread ( resource $handle , int $length )文件系统指针,是典型地由 fopen() 创建的 resource (资源)。
ftell 返回文件指针读/写的位置 int ftell ( resource $handle )
fwrite 写入文件(可安全用于二进制文件) int fwrite ( resource $handle , string $string [, int $length ] )
is_dir 判断给定文件名是否是一个目录 bool is_dir ( string $filename )
is_file 判断给定的文件名是否是一个正常的文件 bool is_file ( string $filename )
is_readable 判断给定文件名是否可读 bool is_readable ( string $filename )
is_writeable 判断给定文件名是否可写 bool is_writeable ( string $filename )
is_executable 判断给定文件名是否可执行 bool is_executable ( string $filename )
mkdir 新建目录 bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = false [, resource $context ]]] )
move_uploaded_file 将上传文件移动到新位置 bool move_uploaded_file ( string $filename , string $destination ) 检查并确保由 filename 指定的文件是合法的上传文件(即通过 PHP 的 HTTP POST 上传机制所上传的
readfile 输出文件 int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )读入一个文件并写入到输出缓冲。 
rename 重命名一个文件或目录 bool rename ( string $oldname , string $newname [, resource $context ] )
rmdir 删除目录 bool rmdir ( string $dirname [, resource $context ] )尝试删除指定目录,该目录必须是空。
tmpfile 建立一个临时文件 resource tmpfile ( void )
unlink 删除文件 bool unlink ( string $filename [, resource $context ] )
     
explode 使用一个字符串分割另一个字符串  array explode ( string $delimiter , string $string [, int $limit ] )
end 将数组的内部指针指向最后一个单元

mixed end ( array &$array )

返回数组中最后一个元素

readdir 从目录句柄中读取条目  string readdir ([ resource $dir_handle ] )返回目录中下一个文件的文件名。文件名以在文件系统中的排序返回。 
opendir 打开目录句柄  resource opendir ( string $path [, resource $context ] )打开一个目录句柄,可用于之后的 closedir() , readdir() 和 rewinddir() 调用中。 
closedir 关闭目录句柄 void closedir ( resource $dir_handle )必须是opendir打开的
empty 检查一个变量是否为空 bool empty ( mixed $var )
touch 设定文件的访问修改时间 bool touch ( string $filename [, int $time = time() [, int $atime ]] )
     

 

四、相关操作

以下操作都是在index.php中建立相关函数,进行调用,操作的目录是index.php同级的 File 目录(可以事先在File文件夹里建立子目录和文件)。

调用方法可以直接使用print_r打印出返回信息。

1.新建文件

    echo file_mkdir("./File/text3.txt");

    /*
    * 新建文件
    * $path 路径+文件名
    * 返回 操作信息
    */
    function file_mkdir($file_name){
        // 1.文件名的合法性:不能包含 /:*"<>|特殊符号
        $pattern = '/[\/:\*"<>\?\|]/';
        // basename 返回路径中文件名部分
        if( !preg_match($pattern, basename($file_name)) ){ // 正则表达式,检查文件名是否合法
            // 2.是否有同名文件  (有的话就提示) file_exists 检查文件或目录是否存在
            if( !file_exists($file_name) ){
                // 创建文件  touch
                if(touch($file_name)){
                    return "创建成功";
                }else{
                    return "创建失败";
                }
            }else{
                return "存在同名文件";
            }
        }else{
            return "文件名不合法";
        }
    }

 

2.新建文件夹

    echo dir_mkdir("./File/text3");

    /*
    * 新建文件夹
    * $path 路径+文件名
    * 返回 操作信息
    */
    function dir_mkdir($path="", $mode = 0777, $recursive = true){
        clearstatcache(); //清除文件缓存
        // 1.文件名的合法性:不能包含 /:*"<>|特殊符号
        $pattern = '/[\/:\*"<>\?\|]/';
        // basename 返回路径中文件名部分
        if( !preg_match($pattern, basename($path)) ){ // 正则表达式,检查文件名是否合法
            if(!file_exists($path)){
                if(mkdir($path, $mode, $recursive)){
                    return "创建成功"; //filename 所指定文件的模式改成 mode 所给定的。
                }else{
                    return "创建失败"; //无法创建文件夹
                }
            }
            return "存在同名文件";
        }else{
            return "文件名不合法"; 
        }
    }

 

3.向文件中写入内容

    echo file_modify("./File/text.txt", "写入成功!@");

    /*
     * 修改文件内容
     * $file_name 路径+文件名 $text 内容
     * 返回值 操作信息
     */
    function file_modify($file_name, $text){
        if(is_file($file_name)){
            $myfile = fopen($file_name, "w") or die("Unable to open file!");
            $file = fwrite($myfile, $text);
            fclose($myfile); //关闭文件

            if($file != 1){
                return "写入成功";
            }else{
                return "写入失败";
            }
        }else{
            return "文件不存在";
        }
    }

 

4.读取文件中内容

    print_r( file_modify("./File/1.txt"));

    // 逐行读取文件内容
    $file = fopen("./File/1.txt","r");
    while ($text = fgets($file)) {
        echo $text;
        echo "<br>";
        echo "<hr>";
    }
    fclose($file);
    /*
     * 读取文件中全部内容写入字符串
     * $file_name 路径+文件名
     * 返回值 文件内容
     */
    function file_modify($file_name){
        if(is_file($file_name)){
            echo $file_name;
            $file = file_get_contents($file_name);
            if($file != ""){
                return $file;
            }else{
                return "读取失败";
            }
        }else{
            return "文件不存在";
        }
    }

 

5.读取一个目录中的内容:

    $path = "File";

    $arr = readDirectory($path);
    print_r($arr); //输出目录中的文件/目录
        /*
     * readDirectory
     * $path 目录路径
     * 说明:遍历一个目录,返回目录中的文件、文件夹名
     */
    function readDirectory($path){
        $arr = array();
        if(file_exists($path)){ //判断是否存在这个目录
            if(is_dir($path)){ //判断是否是一个目录
                $handle = opendir($path); //打开一个目录
                // $item = readdir($handle);  //读取目录中的内容
                while ( ($item = readdir($handle) ) !== false) { // 一定要用!==,因为如果某个文件名如果叫’0′ readdir依次读取目录中的内容
                    // 特殊目录 .  ..要去除
                    if( $item != "."  && $item != ".."){
                        // 判断是否是一个文件夹
                        if( is_dir($path."/".$item) ){
                            // 确定是一个文件夹
                            $arr['dir'][]['name'] = $item;
                        }
                        // 判断是否是一个文件
                        if( is_file($path."/".$item) ){
                            // 确定是一个文件
                            $arr['file'][]['name'] = $item;
                        }
                    }
                }
                closedir($handle); //关闭目录
            }
        }

        return $arr;
    }

 

6.获取目录中所有文件、目录的属性:

    date_default_timezone_set('Asia/Shanghai'); //使用时间函数要设定时区
    $path = "File";

    $arr = readDirectory($path);
    print_r($arr); //输出目录中的文件/目录

    print_r(Traversal_file($arr, $path)); //输出目录中文件/目录属性

    /************************* 以 下 是 相 关 函 数 部 分 *****************************/
    
    /*
     * readDirectory
     * $path 目录路径
     * 说明:遍历一个目录,返回目录中的文件、文件夹名
     */
    function readDirectory($path){
        $arr = array();
        if(file_exists($path)){ //判断是否存在这个目录
            if(is_dir($path)){ //判断是否是一个目录
                $handle = opendir($path); //打开一个目录
                // $item = readdir($handle);  //读取目录中的内容
                while ( ($item = readdir($handle) ) !== false) { // 一定要用!==,因为如果某个文件名如果叫’0′ readdir依次读取目录中的内容
                    // 特殊目录 .  ..要去除
                    if( $item != "."  && $item != ".."){
                        // 判断是否是一个文件夹
                        if( is_dir($path."/".$item) ){
                            // 确定是一个文件夹
                            $arr['dir'][]['name'] = $item;
                        }
                        // 判断是否是一个文件
                        if( is_file($path."/".$item) ){
                            // 确定是一个文件
                            $arr['file'][]['name'] = $item;
                        }
                    }
                }
                closedir($handle); //关闭目录
            }
        }

        return $arr;
    }

    /*
     * 遍历输出文件名调用获取文件基本信息的方法
     * 返回时一个三维数组
     */
    function Traversal_file($arr, $Path){
        // 获取文件的属性
        if( isset($arr['file']) && $arr['file'] ){
            foreach ($arr['file'] as $key => $value) {
                $file_name = $value['name'];
                $arr['file'][$key]['attribute'] = file_Attribute($file_name, $Path);
            }
        }

        // 获取目录的属性
        if( isset($arr['dir']) && $arr['dir'] ){
            foreach ($arr['dir'] as $key => $value) {
                $file_name = $value['name'];
                $arr['dir'][$key]['attribute'] = file_Attribute($file_name, $Path);
            }
        }
        return $arr;
    }

    /*
     * 获取文件基本信息
     * $file_name 文件/目录名
     * $Path 路径
     * 返回值是一个属性数组
     */
    function file_Attribute($file_name, $Path)
    {
        $arr = array();
        $file_name = $Path."/".$file_name;
        if(file_exists($file_name)){ //判断文件或目录是否存在
            $arr['file_name'] = $Path;
            $arr['filetype'] = filetype($file_name); //文件类型
            $arr['transByt'] = transByt(filesize($file_name)); //文件大小
            $arr['is_readable'] =  is_readable($file_name); //可读
            $arr['is_writeable'] = is_writeable($file_name); //可写
            $arr['is_executable'] = is_executable($file_name); //可执行
            $arr['filectime'] = date("Y-m-d H:i:d", filectime($file_name)); //创建时间
            $arr['filemtime'] = date("Y-m-d H:i:d", filemtime($file_name)); //修改时间
            $arr['fileatime'] = date("Y-m-d H:i:d", fileatime($file_name)); //上传访问时间
        }else{
            $arr['file_name'] = "";
            $arr['filetype'] = ""; //文件类型
            $arr['transByt'] = ""; //文件大小
            $arr['is_readable'] =  ""; //可读
            $arr['is_writeable'] = ""; //可写
            $arr['is_executable'] = ""; //可执行
            $arr['filectime'] = ""; //创建时间
            $arr['filemtime'] = ""; //修改时间
            $arr['fileatime'] = ""; //上传访问时间
        }
        return $arr;
    }

    /*
     * 字节大小转换
     * $size输出的字节 整数
     * 输出保留两位小数的字节
     */
    function transByt($size){
        //大小转换  Bytes/Kb/Mb/Gb/Tb/Eb
        $arr = array("Byet", "KB", "MB", "GB", "TB", "EB");
        $i = 0;
        while ($size > 1024) {
            $size = $size / 1024;
            $i ++;
        }
        return round($size, 2).$arr[$i]; //结果保留两位小数
    }

 

7.删除文件操作

    if(file_delete("./File/text.txt")){
        echo "删除成功!";
    }else{
        echo "删除失败";
    }

    /*
    * 删除文件
    * $Path 需要删除的文件
    * 返回值 true 删除成功、 false删除失败
    */
    function file_delete( $Path = '')
    {
        if(!empty($Path)){ //判断变量是否为空
            if( is_file($Path) ){ //检查是否存在这个文件
                // 文件删除
                if(unlink($Path)){
                    return true;
                }else{
                    return false;
                }
            }else{
                return false; 
            }

        }else{
            return false; 
        }
    }

 

8.删除目录,因为rmdir只能删除为空的目录,所有需要递归的方式删除目录中的所有内容

    if(dir_delete("./File/text")){
        echo "删除成功!";
    }else{
        echo "删除失败";
    }

    /*
    * 删除目录
    * $Path 需要删除的目录名
    * 返回值 true 删除成功、 false删除失败
    */
    function dir_delete( $Path = '')
    {
        if(!empty($Path)){ //判断变量是否为空
            if(is_dir($Path)){ //检查是否存在这个文件或目录
                // 删除目录需要先删除目录中的文件、子目录
                $dh = opendir($Path); //打开一个目录
                while ( $file = readdir($dh) ) {
                    if( $file != "." && $file != ".."){
                        $fullpath=$Path."/".$file;
                        if(is_file($fullpath)){
                            // 这是文件
                            unlink($fullpath);
                        }else{
                            // 目录还需要判断是否为空
                            dir_delete ( $fullpath );
                        }
                    }
                }
                closedir($dh); // 关闭用opendir打开的目录

                // 删除单前目录  rmdir只能删除为空的目录
                if(rmdir($Path)){ 
                    return true;
                }else{
                    return false;
                }
            }else{
                return false; 
            }

        }else{
            return false; 
        }
    }

 

9.文件、目录重命名

    echo file_rename("./File/text", "./File/text1/text");

    /*
    * 可以用作文件、目录的移动(剪切)
    * 重命名文件、目录
    * $Path 需要删除的目录名
    * 返回值 操作信息
    */
    
    function file_rename( $oldname, $newname )
    {
        $pattern = '/[\/:\*"<>\?\|]/';
        // basename 返回路径中文件名部分
        if( !preg_match($pattern, basename($newname)) ){

            if(file_exists($oldname)){ // 判断是否存在
                if(!file_exists($newname)){ // 不存在这个文件才执行
                    // 重命名
                    if(rename($oldname, $newname)){
                        return "重命名成功!";
                    }else{
                        return "重命名成功!";
                    }
                }else{
                    // 有同名文件
                    return "有同名文件";
                }

            }else{
                return "不存在操作的文件";
            }
        }else{
            return "文件名不合法!";
        }
    }









当前没有评论