Table of Contents
读取文件内容
判断文件是否存在
写入内容到文件
取得文件的修改时间
取得文件的大小
删除文件

PHP文件系统

Jun 23, 2016 pm 01:30 PM

读取文件内容

PHP具有丰富的文件操作函数,最简单的读取文件的函数为file_get_contents,可以将整个文件全部读取到一个字符串中。

$content = file_get_contents('./test.txt');
Copy after login

file_get_contents也可以通过参数控制读取内容的开始点以及长度。

$content = file_get_contents('./test.txt', null, null, 100, 500);
Copy after login

PHP也提供类似于C语言操作文件的方法,使用fopen,fgets,fread等方法,fgets可以从文件指针中读取一行,freads可以读取指定长度的字符串。

$fp = fopen('./text.txt', 'rb');while(!feof($fp)) {    echo fgets($fp); //读取一行}fclose($fp);
Copy after login

$fp = fopen('./text.txt', 'rb');$contents = '';while(!feof($fp)) {    $contents .= fread($fp, 4096); //一次读取4096个字符}fclose($fp);
Copy after login

使用fopen打开的文件,最好使用fclose关闭文件指针,以避免文件句柄被占用。

判断文件是否存在

一般情况下在对文件进行操作的时候需要先判断文件是否存在,PHP中常用来判断文件存在的函数有两个is_file与file_exists.

$filename = './test.txt';if (file_exists($filename)) {    echo file_get_contents($filename);}
Copy after login

如果只是判断文件存在,使用file_exists就行,file_exists不仅可以判断文件是否存在,同时也可以判断目录是否存在,从函数名可以看出,is_file是确切的判断给定的路径是否是一个文件。

$filename = './test.txt';if (is_file($filename)) {    echo file_get_contents($filename);}
Copy after login

更加精确的可以使用is_readable与is_writeable在文件是否存在的基础上,判断文件是否可读与可写。

$filename = './test.txt';if (is_writeable($filename)) {    file_put_contents($filename, 'test');}if (is_readable($filename)) {    echo file_get_contents($filename);}
Copy after login

写入内容到文件

与读取文件对应,PHP写文件也具有两种方式,最简单的方式是采用file_put_contents。

$filename = './test.txt';$data = 'test';file_put_contents($filename, $data);
Copy after login

上例中,$data参数可以是一个一维数组,当$data是数组的时候,会自动的将数组连接起来,相当于$data=implode('', $data);

同样的,PHP也支持类似C语言风格的操作方式,采用fwrite进行文件写入。

$fp = fopen('./test.txt', 'w');fwrite($fp, 'hello');fwrite($fp, 'world');fclose($fp);
Copy after login

取得文件的修改时间

文件有很多元属性,包括:文件的所有者、创建时间、修改时间、最后的访问时间等。

fileowner:获得文件的所有者filectime:获取文件的创建时间filemtime:获取文件的修改时间fileatime:获取文件的访问时间
Copy after login

其中最常用的是文件的修改时间,通过文件的修改时间,可以判断文件的时效性,经常用在静态文件或者缓存数据的更新。

$mtime = filemtime($filename);echo '修改时间:'.date('Y-m-d H:i:s', filemtime($filename));
Copy after login

取得文件的大小

通过filesize函数可以取得文件的大小,文件大小是以字节数表示的。

$filename = '/data/webroot/usercode/code/resource/test.txt';$size = filesize($filename);
Copy after login

如果要转换文件大小的单位,可以自己定义函数来实现。

function getsize($size, $format = 'kb') {    $p = 0;    if ($format == 'kb') {        $p = 1;    } elseif ($format == 'mb') {        $p = 2;    } elseif ($format == 'gb') {        $p = 3;    }    $size /= pow(1024, $p);    return number_format($size, 3);}$filename = '/data/webroot/usercode/code/resource/test.txt';$size = filesize($filename);$size = getsize($size, 'kb'); //进行单位转换echo $size.'kb';
Copy after login

值得注意的是,没法通过简单的函数来取得目录的大小,目录的大小是该目录下所有子目录以及文件大小的总和,因此需要通过递归的方法来循环计算目录的大小。

删除文件

跟Unix系统命令类似,PHP使用unlink函数进行文件删除。

unlink($filename);
Copy after login

删除文件夹使用rmdir函数,文件夹必须为空,如果不为空或者没有权限则会提示失败。

rmdir($dir);
Copy after login

如果文件夹中存在文件,可以先循环删除目录中的所有文件,然后再删除该目录,循环删除可以使用glob函数遍历所有文件。

foreach (glob("*") as $filename) {   unlink($filename);}
Copy after login

版权声明:本文为博主原创文章,未经博主允许不得转载。

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles