Home > Backend Development > PHP Tutorial > PHP Basic Tutorial 15: File and Directory Operations

PHP Basic Tutorial 15: File and Directory Operations

黄舟
Release: 2023-03-06 09:08:01
Original
1579 people have browsed it


Preface


#When we are developing, sometimes we need to upload and download pictures and files. For example, when registering an account, sometimes you need to upload a picture of your avatar. At this time, you need to use file processing, and there are many file styles, such as txt, word, excel, etc.

File transmission method

The way of operating files in PHP language and even other languages ​​is essentially a stream operation. There are two types of streams in PHP (byte stream, binary stream), which are divided into input streams and output streams according to different output methods.
PHP Basic Tutorial 15: File and Directory Operations
File streams are all referenced by memory. If the data is saved from memory to a file on disk, we call it an output stream. Conversely, if the data flows from a file to memory, we call it an output stream. input stream.

File operation methods

There are two ways to operate files in PHP

  • Local operation

  • Remote operation

Local operation is to add, delete, modify and check files on your own computer.

Remote operation is to access the server remotely and perform operations such as adding, deleting, modifying and checking files on the server.

You can see the functions for operating files from the help document:

PHP Basic Tutorial 15: File and Directory Operations

Here are just some of the functions listed. For more functions, please see the help. document. You can see that there are a total of 81 functions in the help document, but we don’t need to master them all, just the commonly used ones.

Operation of files

Reading the relevant information of the file

When we operate the file, sometimes we need to know the relevant information of the file, such as the size of the file, the Type, file creation time, modification time, access time and other information, here the technology of reading file-related information will be used, which is divided into two forms in PHP to obtain file information.

The first way to read file-related information

<?php

    //写一个变量记录文件的路径
    $file_path = "D:/config.txt";

    if(file_exists($file_path)){
        //文件存在
        if($fp = fopen($file_path,&#39;r&#39;)){
            //$type是一个存放文件信息的数组
            $type = fstat($fp);
            echo &#39;<br>文件的字节是:&#39; . $type[&#39;size&#39;];
            echo &#39;<br>文件创建时间是:&#39; . date(&#39;Y-m-d H:i:s&#39;,$type[&#39;ctime&#39;]);
            echo &#39;<br>文件访问时间是:&#39; . date(&#39;Y-m-d H:i:s&#39;,$type[&#39;atime&#39;]);
            echo &#39;<br>文件修改时间是:&#39; .date(&#39;Y-m-d H:i:s&#39;,$type[&#39;mtime&#39;]);
            //关闭资源
            fclose($fp);
        }else{
            echo &#39;文件打开失败&#39;;
        }
    }else{
        echo &#39;文件不存在&#39;;
    }
    ......结果.......
    文件的字节是:22
    文件创建时间是:2016-10-12 20:34:56
    文件访问时间是:2016-10-12 20:34:56
    文件修改时间是:2016-10-12 20:35:08
Copy after login

1. We first define a path to the file we access. This path can be a relative path or an absolute path.
2. Use the file_exists($path) function to determine whether the file exists. If it exists, it returns true. If it does not exist, it returns false.
3. Through fopen($path, access form), this function opens a file and returns a file. Pointer, pointing to the first row. The first parameter is the path of the file, the second parameter is the access form of the file, "r" means reading the file.
4. fstat (file pointer) obtains file information through the opened file pointer and returns an array, which contains some associative arrays with the values ​​we want.
5. Remember to close the resource after using it, otherwise unexpected errors may sometimes occur.

The second way to read file information

<?php

    $file_path = &#39;D:/config.txt&#39;;
    echo &#39;<br>文件的类型是:&#39; . filetype($file_path);
    echo &#39;<br>文件的大小是:&#39; . filesize($file_path);
    echo &#39;<br>文件的创建时间是:&#39; . date(&#39;Y-m-d H:i:s&#39;,filectime($file_path));
    echo &#39;<br>文件的访问时间是:&#39; .date(&#39;Y-m-d H:i:s&#39;,fileatime($file_path));
    echo &#39;<br>文件的修改时间是:&#39; . date(&#39;Y-m-d H:i:s&#39;,filemtime($file_path));
    .....结果.....
    文件的类型是:file
    文件的大小是:22
    文件的创建时间是:2016-10-12 20:34:56
    文件的访问时间是:2016-10-12 20:34:56
    文件的修改时间是:2016-10-12 20:35:08
Copy after login

This method is relatively simple. It directly obtains the relevant information of the file through functions, but the file should be opened at the bottom of each function. operate.

Read the contents of the file

We often need to read the contents of the file when operating files. PHP provides three ways to read files.

The first way to read a file

<?php
    header("Content-type:text/html;charset = utf-8");
    $file_path = &#39;D:/config.txt&#39;;

    if(file_exists($file_path)){

        if($fp = fopen($file_path,&#39;r&#39;)){
            //获取文件的大小
            $file_size = fstat($fp)[&#39;size&#39;];
            $content = fread($fp, $file_size);
            //对文件中中文进行编码
            $content = iconv(&#39;gbk&#39;, &#39;utf-8&#39;, $content);
            //对换行符进行替换。
            $content = str_replace("\r\n", "<br>", $content);
            echo $content;
            fclose($fp);
        }else{
            echo &#39;文件打开失败&#39;;
        }
    }else{
        echo &#39;文件不存在&#39;;
    }
    ......结果.......
    这是一些配置文件信息。
    user = abc;
    password = 122;
Copy after login
  • Define the full path of the file

  • file_exists($path) judgment Does the file exist?

  • fopen($path, access form) There are many access forms in this function. We only use three commonly used ones:

    1. r, for reading the file, the file pointer points to the head

    2. w, for writing the file, if the file exists, the file pointer points to the head, and Clear the contents and create the file if it does not exist.

    3. a, perform a writing operation on a file. If the file exists, the file pointer points to the end, and the content inside will not be cleared. If the file does not exist, the file will be created.

  • fread(file pointer, size) This function is to perform file operations. By getting the file size, write the whole of a file. into $content.

  • iconv (input character set, output character set, string) This function encodes the function in the file and stores it in the file in gbk and in the page. It is utf-8,

  • str_replace (character to be replaced, ring character, string). This function converts the newline character in the file. The newline character in the file under Windows is "\r\n", the content of the file is displayed on the web page, and the line break character of the web page is "<\br>". Note that the escape characters must be enclosed in double quotes.

  • Close the file pointer resource

The second way to read the file

In the first way, read Fetching the file is to read the entire file at once. When the file is very large, this method is unreasonable. You can use the second method, using loop reading, reading a part first, merging, and then reading a part, merging.

<?php

    $file_path = &#39;D:/config.txt&#39;;

    if(file_exists($file_path)){
        if($fp = fopen($file_path,&#39;r&#39;)){
            //文件太大,分字节度
            $size = 1024;//每次读取1024个字节
            $tmp_content = &#39;&#39;;//存放一次读取的内容
            $content = &#39;&#39;;//存放总的内容。
            while(!feof($fp)){
                $tmp_content = fread($fp,$size);
                $content .= $tmp_content;
            }

            $content = iconv(&#39;gbk&#39;, &#39;utf-8&#39;, $content);
            $content = str_replace("\r\n", "<br>", $content);
            echo $content;
            fclose($fp);

        }else{
            echo &#39;文件打开失败&#39;;
        }

    }else{
        echo &#39;文件不存在&#39;;
    }
    ......结果.......
    这是一些配置文件信息。
    user = abc;
    password = 122;
Copy after login

- 从上面的代码中可以看出来,读取文件的内容是分块读取的,读取一次,拼接到总的内容上。
- feof(文件指针) 测试文件指针是否到了文件结束的位置,当文件指针指向最后则不用循环。
- 关闭文件指针资源

读取文件的第三种方式

<?php
    $file_path = &#39;D:/config.txt&#39;;
    $content =  file_get_contents($file_path);
    $content = iconv(&#39;gbk&#39;,&#39;utf-8&#39;,$content);
    $content = str_replace("\r\n","<br>",$content);
    echo $content;
    ......结果.......
    这是一些配置文件信息。
    user = abc;
    password = 122;
Copy after login

第三种方式是最简单的一种方式,通过file_get_contents()方法进行整体的读取。

创建文件和写文件

创建文件和写文件第一种方式

<?php
    //定义文件的路径
    $file_path = &#39;D:/test.txt&#39;;

    if(!file_exists($file_path)){
        //文件不存在
        //fopen()函数使用w这种访问形式,
        if($fp = fopen($file_path, &#39;w&#39;)){
            $str = &#39;&#39;;
            for($i = 0; $i < 10; $i++){
                $str .= "hello,php\r\n";
            }
            //向文件中写数据
            fwrite($fp, $str);
            fclose($fp);
        }
    }
Copy after login

- 当文件不存在的使用使用fopen()打开文件是自动创建文件的,这里使用的文件访问形式是w,文件指针指向头部,清空文件里面的内容。
- 通过fread()函数想文件中写文件。
- 当文件存在的时候我们可以使用’a’这种访问形式进行对文件内容的追加写入。

创建文件和写文件第二种方式

<?php
    //定义文件的路径
    $file_path = &#39;D:/test.txt&#39;;

    if(!file_exists($file_path)){
        $str = &#39;&#39;;
        for($i = 0; $i < 10; $i++){
            $str .= "hello,php\r\n";
        }

        file_put_contents($file_path, $str);

    }
Copy after login

- 使用file_put_contents()函数进行文件的写入,这个函数也是当文件不存在的时候,创建文件。
- 如果我们通过file_put_contents函数来追加新的内容到文件中,应该在使用file_put_contents函数时,带上第三个参数 FILE_APPEND 即可。

删除文件

<?php
    $file_path = &#39;D:/test.txt&#39;;

    if(file_exists($file_path)){
        if(unlink($file_path)){
            echo &#39;文件删除成功&#39;;
        }else{
            echo &#39;文件删除失败&#39;;
        }
    }
Copy after login

- 通过unlink(文件路径)函数删除文件。

修改文件的名字

<?php
    $file_path = &#39;D:/test.txt&#39;;
    $file_newPath = &#39;D:/newtest.txt&#39;;

    if(file_exists($file_path)){
        if(rename($file_path,$file_newPath)){
            echo &#39;文件名修改成功&#39;;
        }else{
            echo &#39;文件名修改失败&#39;;
        }
    }
Copy after login

- 修改文件的名字可以通过rename(

新的文件名)进行修改,当修改成功时返回true,失败返回false。这个函数还可以移动文件的位置。


对目录的操作

在php文件编程中,目录也是一种文件,是一种比较特殊的文件,因此对目录的操作有固定的操作方法,主要的方法有三个 is_dir,rmdir,mkdir

  • is_dir 判断是否是一个目录

  • rmdir 删除一个目录,当目录下面有文件或目录的时候不能删除。

  • mkdir 创建一个目录

    <?php
    
        $dir_path = &#39;D:/test&#39;;
        //判断目录是否存在
        if(is_dir($dir_path)){
            echo &#39;目录存在&#39;;
        }else{
            //目录不存在,创建目录
            if(mkdir($dir_path)){
                echo &#39;目录创建成功&#39;;
            }else{
                echo &#39;目录创建失败&#39;;
            }
        }
    Copy after login
  • 上面先判断目录是否存在,不存在使用mkdir()函数进行目录的创建。

上面的代码只能创建一级目录,当路径名字换成$dir_path = ‘D:/test/a/b/c/d’时,在test目录下还有目录,这时候用上面的方法就会报错,不能够创建多级目录。这时候也可以使用mkdir()函数进行创建,但是在函数中多了两个参数,这两个参数对于windows系统下开发是没有意义的。

<?php

    $dir_path = &#39;D:/test/a/b/c/d&#39;;
    //判断目录是否存在
    if(is_dir($dir_path)){
        echo &#39;目录存在&#39;;
    }else{
        //目录不存在,创建目录
        if(mkdir($dir_path,0777,true)){
            echo &#39;目录创建成功&#39;;
        }else{
            echo &#39;目录创建失败&#39;;
        }
    }
Copy after login
  • 可以看到在创建目录的函数中添加了两个参数,就能创建多级目录。0777是在linux下的最大访问权限,而true是表示创建多级目录。

删除目录

<?php
    $dir_path = &#39;D:/test&#39;;

    if(is_dir($dir_path)){
        //目录存在
        if(rmdir($dir_path)){
            echo &#39;目录删除成功&#39;;
        }else{
            echo &#39;目录删除失败&#39;;
        }
    }
Copy after login

- 通过rmdir(目录路径)删除目录。
- 删除目录时,下面没有目录或者文件的存在。
- rmdir()函数只能删除一个目录,不能删除多个目录,删除多个目录,可以使用递归删除。

    <?php

        //在这里test目录下的全目录是:D:/test/a/b/c/d
        $dir_path = &#39;D:/test&#39;;
        delDir($dir_path);
        function delDir($dir_path){
            //打开当前的目录
            $dir = opendir($dir_path);
            //通过readdir函数获取目录下的所有目录
            while(false !== ($fileName = readdir($dir))){
                //对当前的目录进行拼接
                if($fileName != &#39;.&#39; && $fileName != &#39;..&#39;){
                    $dir_name = $dir_path . &#39;/&#39; . $fileName;
                    if(is_dir($dir_name)){
                        //是一个目录,通过递归在此判断。
                        delDir($dir_name);
                        //递归完成,当前目录下为空,删除目录。
                    }else if(is_file($dir_name)){
                        //是文件删除文件。
                        unlink($dir_name);
                    }
                }

            }
            closedir($dir);
            rmdir($dir_path);
        }
Copy after login

把文件删除的操作封装到函数中,如果目录下没有文件则while循环不会进入循环,而是直接删除目录。当有目录或文件时,可以在循环中递归的执行函数,知道遇到是文件或目录为空(基准条件)。

文件的拷贝

<?php
    //当前需要复制的文件路径。
    $file_path = &#39;D:/Desert.jpg&#39;;
    //需要复制到哪的路径
    $path = "E:/desert.jpg";
    if(file_exists($file_path)){
        if(copy($file_path,$path)){
            echo &#39;复制成功&#39;;
        }else{
            echo &#39;复制失败&#39;;
        }

    }else{
        echo &#39;文件不存在&#39;;
    }
Copy after login
  • 定义的文件的全路径

  • 定义目标的路径。

  • 利用copy函数直接进行复制拷贝,第一个参数是文件的路径,第二个参数是目标的路径。

遍历目录

<?php

    $dir_path = &#39;D:/test&#39;;
    isDir($dir_path);
    function isDir($dir_path){
        if(is_dir($dir_path)){
            //存在文件
            $dir = opendir($dir_path);
            //打开目录
            while(($fileName = readdir($dir)) !== false){
                if($fileName != &#39;.&#39; && $fileName != &#39;..&#39;){
                    if(is_dir($dir_path . &#39;/&#39; . $fileName)){
                        echo &#39;<br>目录名是:&#39; . $fileName;
                        isDir($dir_path . &#39;/&#39; . $fileName);
                    }else if(is_file($dir_path . &#39;/&#39; . $fileName)){
                        echo &#39;<br>文件名是:&#39; . $fileName;
                    }
                }

            }
            //关闭资源
            closedir($dir);
        }
    }
    ......结果.......
    目录名是:a
    文件名是:a.txt
    目录名是:b
    目录名是:c
    目录名是:d
    文件名是:n.doc
    文件名是:c.txt
Copy after login

* 通过递归进行循环的判断一个目录下面的所有目录和文件,进行输出。
* 在每个目录下都隐藏着两个无用的目录,所以通过if判断把这两个无用的目录过滤掉。

统计目录的大小。

<?php

    $dir_path = &#39;D:/test&#39;;
    echo getSize($dir_path);

    function getSize($dir_path){
        //定义字节。
        $size = 0;
        //判断是否目录
        if(is_dir($dir_path)){
            //打开目录
            $dir = opendir($dir_path);

            //判断每个目录是否存在。
            while(false !== ($fileName = readdir($dir))){
                //过滤无用的两个目录。
                if($fileName != &#39;.&#39; && $fileName != &#39;..&#39;){

                    if(is_dir($dir_path . &#39;/&#39; . $fileName)){
                        //通过递归进行循环的获取字节大小。
                        $size += getSize($dir_path . &#39;/&#39; . $fileName); 

                    }else if(is_file($dir_path . &#39;/&#39; . $fileName)){

                        $size +=filesize($dir_path . &#39;/&#39; . $fileName);
                    }
                }
            }
        }
        //关闭资源。
        fclose($dir);
        return $size;
    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
    .......结果.......
    47
Copy after login

PHP Basic Tutorial 15: File and Directory Operations

  • 获取目录的字节通过递归完成。定义$size记录每个文件的大小,返回。

总结

PHP中对于文件的操作还是很重要的,对于文件的操作要灵活的应用不同的函数。

 以上就是PHP基础教程十五之文件、目录的操作的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template