Table of Contents
1 Get file information
1.1 The first way (fopen, fstat, file_exists)
1.2 The second way
2 Read the file content
2.1 The first way, fread
2.2 The second way, feof
2.3 The third way, file_get_contents
3 Create a file and write the content
3.1 Case 1
3.2 Case 2, file_put_contents
4 Delete file
5 Modify file name
6 Operate file directory
6.1 Create a first-level directory
6.2 Create a multi-level directory
6.3 Delete a directory (first level)
7 Application cases of file programming
7.1 How to copy a picture
7.2 Traverse a folder and determine whether the contents under the folder are directories and files
7.3 Write a function to count the size of all files in a directory
7.4 Delete a directory
Home Backend Development PHP Tutorial Introduction to PHP file programming

Introduction to PHP file programming

Jul 05, 2018 am 10:11 AM

This article mainly introduces the introduction to PHP file programming. It has certain reference value. Now I share it with everyone. Friends in need can refer to it

1 Get file information

1.1 The first way (fopen, fstat, file_exists)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<?php

$file_full_path = &#39;./test.txt&#39;;

if(file_exists($file_full_path)){       // 检查文件或目录是否存在,存在则返回 TRUE,否则返回 FALSE

    $fp = fopen($file_full_path, &#39;r&#39;);  // 打开文件或url,成功时返回文件指针资源,如果打开失败,本函数返回 FALSE。

    $fileinfo_arr = fstat($fp);         // 通过已打开的文件指针取得文件信息,返回一个数组具有该文件的统计信息

 

    echo &#39;<pre class="brush:php;toolbar:false">&#39;;

    var_dump($fileinfo_arr);

 

    echo &#39;文件的大小是:&#39; . $fileinfo_arr[&#39;size&#39;] . &#39;个字节&#39;;

    echo &#39;文件的创建时间是:&#39; . date(&#39;Y-m-d H:i:s&#39;, $fileinfo_arr[&#39;ctime&#39;]);

    echo &#39;文件的访问时间是:&#39; . date(&#39;Y-m-d H:i:s&#39;, $fileinfo_arr[&#39;atime&#39;]);

    echo &#39;文件的修改时间是:&#39; . date(&#39;Y-m-d H:i:s&#39;, $fileinfo_arr[&#39;mtime&#39;]);

}else{

    echo &#39;文件不存在&#39;;

}

Copy after login

1.2 The second way

1

2

3

4

5

6

7

8

9

10

11

12

<?php

$file_full_path = &#39;./test.txt&#39;;

if(file_exists($file_full_path)){

    echo &#39;文件的大小是:&#39; . filesize($file_full_path);

    echo &#39;文件的类型是:&#39; . filetype($file_full_path);

 

    echo &#39;文件的创建时间是:&#39; . date(&#39;Y-m-d H:i:s&#39;, filectime($file_full_path));

    echo &#39;文件的访问时间是:&#39; . date(&#39;Y-m-d H:i:s&#39;, fileatime($file_full_path));

    echo &#39;文件的修改时间是:&#39; . date(&#39;Y-m-d H:i:s&#39;, filemtime($file_full_path));

}else{

    echo &#39;文件不存在&#39;;

}

Copy after login

2 Read the file content

2.1 The first way, fread

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<?php

$file_full_path = &#39;./test.txt&#39;;

if(file_exists($file_full_path)){

    // 1、打开文件

    $fp = fopen($file_full_path, &#39;r&#39;);

    // 2、获取文件的大小

    $file_size = filesize($file_full_path);

    // 3、读取内容

    $con_str = fread($fp, $file_size);      // 返回所读取的字符串, 或者在失败时返回 FALSE。

    fclose($fp);

    // 替换换行符

    $con_str = str_replace("\r\n", &#39;<br>&#39;, $con_str);

    $con_str = str_replace("\n", &#39;<br>&#39;, $con_str);

    // 替换 tab

    $con_str = str_replace("    ", "    ", $con_str);

 

    echo $con_str;

 

}else{

    echo &#39;文件不存在&#39;;

}

Copy after login

2.2 The second way, feof

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<?php

$file_full_path = &#39;./test.txt&#39;;

if(file_exists($file_full_path)){

    $fp = fopen($file_full_path, &#39;r&#39;);

    // 设置缓冲

    $buffer = &#39;&#39;;

    $buffer_size = 1024;

    $con_str = &#39;&#39;;

 

    while(!feof($fp)){              // 测试文件指针是否到了文件结束的位置,到达返回true,否则返回false

        $buffer = fread($fp, $buffer_size);

        $con_str .= $buffer;

    }

 

    // 关闭文件

    fclose($fp);

    $con_str = str_replace("\r\n", &#39;<br>&#39;, $con_str);

    $con_str = str_replace("\n", &#39;<br>&#39;, $con_str);

    $con_str = str_replace("    ", &#39;    &#39;, $con_str);

    echo $con_str;

}else{

    echo &#39;文件不存在&#39;;

}

Copy after login

2.3 The third way, file_get_contents

1

2

3

4

5

6

7

8

9

10

11

12

13

<?php

$file_full_path = &#39;./test.txt&#39;;

if(file_exists($file_full_path)){

    $con_str = file_get_contents($file_full_path);      //  将整个文件读入一个字符串

 

    $con_str = str_replace("\r\n", &#39;<br>&#39;, $con_str);

    $con_str = str_replace("\n", &#39;<br>&#39;, $con_str);

    $con_str = str_replace("    ", &#39;    &#39;, $con_str);

     

    echo $con_str;

}else{

    echo &#39;文件不存在&#39;;

}

Copy after login

3 Create a file and write the content

3.1 Case 1

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<?php

$file_full_path = &#39;./test.txt&#39;;

if(!file_exists($file_full_path)){

    if($fp = fopen($file_full_path, &#39;w&#39;)){      // 覆盖写入10句helloworld

        $con = &#39;&#39;;

        for($i=0; $i<10; $i++){

            $con .= "HelloWorld\r\n";

        }

 

        // 写入文件

        fwrite($fp, $con);          // fwrite() 返回写入的字符数,出现错误时则返回 FALSE 。

        fclose($fp);

    }else{

        echo &#39;创建文件失败&#39;;

    }

}else{

    echo &#39;文件已经存在&#39;;

}

Copy after login

3.2 Case 2, file_put_contents

1

2

3

4

5

6

7

8

9

10

11

12

<?php

$file_full_path = &#39;./test.txt&#39;;

if(!file_exists($file_full_path)){

    $con = &#39;&#39;;

    for($i=0; $i<10; $i++){

        $con .= "helloworld\r\n";

    }

    // 默认是覆盖写,可以追加FILE_APPEND参数,改为追加写。

    file_put_contents($file_full_path, $con);       // 和依次调用 fopen(),fwrite() 以及 fclose() 功能一样。

}else{

    echo &#39;已经存在该文件&#39;;

}

Copy after login

4 Delete file

1

2

3

4

5

6

7

8

9

10

11

<?php

$file_full_path = &#39;./test.txt&#39;;

if(file_exists($file_full_path)){

    if(unlink($file_full_path)){

        echo &#39;<br>删除成功&#39;;

    }else{

        echo &#39;<br>删除失败&#39;;

    }

}else{

    echo &#39;文件不存在,无法删除&#39;;

}

Copy after login

5 Modify file name

1

2

3

4

5

6

7

8

9

10

11

12

13

<?php

$file_full_path = &#39;./test.txt&#39;;

$file_new_full_path = &#39;./王八.txt&#39;;

$file_new_full_path = iconv(&#39;utf-8&#39;, &#39;gbk&#39;, $file_new_full_path);

if(file_exists($file_full_path)){

    if(rename($file_full_path, $file_new_full_path)){           // 重命名一个文件或目录

        echo &#39;改名成功!&#39;;

    }else{

        echo &#39;改名失败!&#39;;

    }

}else{

    echo &#39;文件不存在&#39;;

}

Copy after login

6 Operate file directory

6.1 Create a first-level directory

1

2

3

4

5

6

7

8

9

10

11

12

13

<?php

$dir_full_path = &#39;./abc&#39;;

 

// 判断有没有该目录

if(!is_dir($dir_full_path)){

    if(mkdir($dir_full_path)){

        echo &#39;创建目录成功!&#39;;

    }else{

        echo &#39;创建目录失败!&#39;;

    }

}else{

    echo &#39;已经存在该目录,无法再次创建&#39;;

}

Copy after login

6.2 Create a multi-level directory

1

2

3

4

5

6

7

8

9

10

11

<?php

$dir_full_path = &#39;./abc/edf/xyz&#39;;

if(!is_dir($dir_full_path)){

    if(mkdir($dir_full_path, 0777, true)){      // true 表示递归创建

        echo &#39;创建目录成功&#39;;

    }else{

        echo &#39;创建目录失败&#39;;

    }

}else{

    echo &#39;已经存在该目录,无法再次创建!&#39;;

}

Copy after login

6.3 Delete a directory (first level)

1

2

3

4

5

6

7

8

9

10

11

<?php

$dir_full_path = &#39;./abc&#39;;

if(is_dir($dir_full_path)){

    if(rmdir($dir_full_path)){

        echo &#39;删除目录成功&#39;;

    }else{

        echo &#39;删除目录失败&#39;;

    }

}else{

    echo &#39;不存在该文件夹&#39;;

}

Copy after login

7 Application cases of file programming

7.1 How to copy a picture

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<?php

$file_src_full_path = &#39;F:/壁纸.jpg&#39;;

$file_src_full_path = iconv(&#39;utf-8&#39;, &#39;gbk&#39;, $file_src_full_path);

 

$file_des_full_path = &#39;D:/amp/WWW/萧山.jpg&#39;;

$file_des_full_path = iconv(&#39;utf-8&#39;, &#39;gbk&#39;, $file_des_full_path);

 

if(file_exists($file_src_full_path)){

    if(copy($file_src_full_path, $file_des_full_path)){

        echo &#39;拷贝成功&#39;;

    }else{

        echo &#39;拷贝失败&#39;;

    }

}else{

    echo &#39;没有这个文件&#39;;

}

Copy after login

7.2 Traverse a folder and determine whether the contents under the folder are directories and files

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<?php

$dir_full_path = &#39;D:/amp/WWW/&#39;;

if(is_dir($dir_full_path)){

    $dir_handle = opendir($dir_full_path);      // 如果成功则返回目录句柄的 resource,失败则返回 FALSE

    while(($file_name = readdir($dir_handle)) !== false){       // 成功则返回文件名 或者在失败时返回 FALSE

        if(is_dir($dir_full_path . $file_name)){

            echo $file_name . &#39;是目录<br>&#39;;

        }else{

            echo $file_name . &#39;是文件<br>&#39;;

        }

    }

 

    closedir($dir_handle);

}else{

    echo &#39;不是目录,无法打开&#39;;

}

Copy after login

7.3 Write a function to count the size of all files in a directory

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

<?php

$dir_name = &#39;D:/amp/WWW&#39;;

function getDirSize($dir_name){

    $dir_size = 0;

    $dir_handle = opendir($dir_name);

    while(($file_name = readdir($dir_handle)) !== false){

        $file = $dir_name . &#39;/&#39; . $file_name;       // 文件全名

        if($file_name!==&#39;.&#39; && $file_name!==&#39;..&#39;){

            if(is_dir($file)){

                $dir_size += getDirSize($file);

            }else{

                $dir_size += filesize($file);

            }

        }

    }

    closedir($dir_handle);

    return $dir_size;

}

 

echo getDirSize($dir_name);

Copy after login

1

<br/>

Copy after login

7.4 Delete a directory

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<?php

$dir_name = &#39;D:/amp/WWW/.idea&#39;;

function rrmdir($src){

    $dir_handle = opendir($src);

    while(false !== ($file = readdir($dir_handle))){

        if(($file != &#39;.&#39;) && ($file != &#39;..&#39;)){

            $full = $src . &#39;/&#39; . $file;

            if(is_dir($full)){

                rrmdir($full);

            }else{

                unlink($full);

            }

        }

    }

    closedir($dir_handle);

    rmdir($src);

}

rrmdir($dir_name);

Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

php code for traversing all files and sub-files in a folder

PHP files and Directory operations

The above is the detailed content of Introduction to PHP file programming. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1237
24
Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

See all articles