search
HomeBackend DevelopmentPHP Tutorial第六章 php目录与文件操作_PHP

一.目录操作
basename -- 返回路径中的文件名部分
dirname -- 返回路径中的目录部分
pathinfo -- 返回文件路径的信息
realpath -- 返回规范化的绝对路径名
复制代码 代码如下:
$path = 'demo1.php';
$path = realpath($path);
echo basename($path);
echo '
';
echo dirname($path);
echo '
';
$array_path = pathinfo($path);
echo 'basename : '.$array_path['basename'].'
';
echo 'dirname : '.$array_path['dirname'].'
';
echo 'extension : '.$array_path['extension'].'
';
echo 'filename : '.$array_path['filename'].'
';
?>

Output:
demo1.php
D:\AppServ\www\Basic6
basename : demo1.php
dirname : D:\AppServ\www\Basic6
extension : php
filename : demo1

二.磁盘、目录和文件计数
1.查看文件大小和磁盘空间
filesize -- 取得文件大小
disk_free_space -- 返回目录中的可用空间
disk_total_space -- 返回一个目录的磁盘总大小
复制代码 代码如下:
$path ='demo2.php';
$path = realpath($path);
$drive = 'c:';
echo round(filesize($path)/1024,2).'kb'.'
';
echo round(disk_free_space($drive)/1024/1024/1024,2).'GB'.'
';
echo round(disk_total_space($drive)/1024/1024/1024,2).'GB'.'
';
?>

output
0.26kb
10.61GB
30.01GB

2.获得文件的各种时间
fileatime -- 取得文件的上次访问时间
filectime -- 取得文件的 inode 修改时间
filemtime -- 取得文件修改时间
复制代码 代码如下:
$file = realpath ( '../Basic5/demo3.php' );
$date_format = 'Y-m-d h:i:s';
echo 'lastest accessing time : '.date ( $date_format, fileatime ( $file ) ) . '
';
echo 'lastest change time : '.date ( $date_format, filectime ( $file ) ) . '
';
echo 'lastest modify time : '.date ( $date_format, filemtime ( $file ) ) . '
';
?>

output
lastest accessing time : 2011-12-18 04:26:49
lastest change time : 2011-12-18 04:26:49
lastest modify time : 2011-12-18 04:29:15

三.文件处理
文件读写的两种方式:
1.php所有版本都支持的方法:
fopen -- 打开文件或者 URL
fclose -- 关闭一个已打开的文件指针
fwrite -- 写入文件(可安全用于二进制文件)
表 1. fopen() 中 mode 的可能值列表

mode

说明

'r'

只读方式打开,将文件指针指向文件头。

'r+'

读写方式打开,将文件指针指向文件头。

'w'

写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。

'w+'

读写方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。

'a'

写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。

'a+'

读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。

'x'

创建并以写入方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。此选项被 PHP 4.3.2 以及以后的版本所支持,仅能用于本地文件。

'x+'

创建并以读写方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。此选项被 PHP 4.3.2 以及以后的版本所支持,仅能用于本地文件。

复制代码 代码如下:
$fp = fopen('file1.txt','w');
$outStr = "my name is anllin,\r\nmy age is 29.";
fwrite($fp,$outStr,strlen($outStr));
fclose($fp);
?>

output
my name is anllin,
my age is 29.
2.php5新加入的方法
file_put_contents -- 将一个字符串写入文件
复制代码 代码如下:
file_put_contents('file2.txt',"my name is anllin,\r\nmy age is 29.");
?>

output
my name is anllin,
my age is 29.
读出文件内容的方法:

函数

功能

Fgetc()

读出一个字符,并将指针移到下一个字符

Fgets()

读出一行字符,可以指定一行显示的长度。

Fgetss()

从文件指针中读取一行并过滤掉HTML标记

Fread()

读取定量的字符

Fpassthru()

输出文件到指定处的所有剩余数据

File()

将整个文件读入数组中,以行分组

Readfile()

读入一个文件并写入到输出缓冲

File_get_contents()

将整个文件读入一个字符串

Feof()

判断读完文件函数

File_exists()

查看文件是否存在

示例文件file1.txt的内容如下:
my name is anllin,
my age is 29.
fgetc -- 从文件指针中读取字符
Demo.php
复制代码 代码如下:
$fp = fopen('file1.txt','r');
echo fgetc($fp);
echo fgetc($fp);
fclose($fp);
?>

Output:
my
fgets -- 从文件指针中读取一行
复制代码 代码如下:
$fp = fopen('file1.txt','r');
echo fgets($fp);
echo fgets($fp);
fclose($fp);
?>

output
my name is anllin, my age is 29.
fgetss -- 从文件指针中读取一行并过滤掉 HTML 标记
复制代码 代码如下:
$fp = fopen('file3.txt','w');
$outStr = "my name is anllin";
fwrite($fp,$outStr,strlen($outStr));
fclose($fp);
$ftp = fopen('file3.txt','r');
echo fgetss($ftp);
fclose($ftp);
?>

Output
my name is anllin
fread -- 读取文件(可安全用于二进制文件)
复制代码 代码如下:
$filename = 'file1.txt';
$fp = fopen($filename,'r');
$contents = fread($fp,filesize($filename));
echo $contents;
fclose($fp);
?>

Output
my name is anllin, my age is 29.
fpassthru -- 输出文件指针处的所有剩余数据
复制代码 代码如下:
$filename = 'file1.txt';
$fp = fopen($filename,'rb');
$leftSize = fpassthru($fp);
echo $leftSize;
fclose($fp);
?>

output
my name is anllin, my age is 29. 33
file -- 把整个文件读入一个数组中
复制代码 代码如下:
$lines = file('file1.txt');
foreach ($lines as $line_num => $line)
{
echo $line_num.' : '.$line.'
';
}
?>

output
0 : my name is anllin,
1 : my age is 29.
readfile -- 输出一个文件
复制代码 代码如下:
$size = readfile('file1.txt');
echo $size;
?>

output
my name is anllin, my age is 29.33
file_get_contents -- 将整个文件读入一个字符串(php5.0新增)
复制代码 代码如下:
$contents = file_get_contents('file1.txt');
echo $contents;
?>

output
my name is anllin, my age is 29.
feof -- 测试文件指针是否到了文件结束的位置
复制代码 代码如下:
$fp = fopen('file1.txt','r');
while(!feof($fp))
{
echo fgetc($fp);
}
fclose($fp);
?>

output
my name is anllin, my age is 29.
file_exists -- 检查文件或目录是否存在
复制代码 代码如下:

$filename = 'file1.txt';
if(file_exists($filename))
{
echo '执行文件读写操作';
}
else
{
echo '你要找的文件不存在';
}
?>

output
执行文件读写操作
filesize -- 取得文件大小
复制代码 代码如下:
$file_size = filesize('file1.txt');
echo $file_size;
?>

output
33
unlink -- 删除文件
复制代码 代码如下:
$isDeleted = unlink('file3.txt');
echo $isDeleted;
?>

output
1
rewind -- 倒回文件指针的位置
ftell -- 返回文件指针读/写的位置
fseek -- 在文件指针中定位
复制代码 代码如下:
$fp = fopen ( 'file1.txt', 'r' );
fgetc ( $fp );
fgetc ( $fp );
echo ftell ( $fp ) . '
';
rewind ( $fp );
echo ftell ( $fp ) . '
';
fgetc ( $fp );
fgetc ( $fp );
echo ftell ( $fp ) . '
';
fseek($fp,0);//same as rewind ($fp)
echo ftell ( $fp ) . '
';
?>

output
2
0
2
0
Flock的操作值

操作值

意义

LOCK_SH(以前为1)

读写锁定。这意味着文件可以共享,其他人可以读该文件

LOCK_EX(以前为2)

写操作锁定。这是互斥的,该文件不能被共享

LOCK_UN(以前为3)

释放已有的锁定

LOCK_NB(以前为4)

防止在请求加锁时发生阻塞

flock -- 轻便的咨询文件锁定
复制代码 代码如下:
$filename = 'file1.txt';
$fp = fopen($filename,'rb');
flock($fp,LOCK_EX);//locked
$contents = fread($fp,filesize($filename));
flock($fp,LOCK_UN);//unlocked
echo $contents;
fclose($fp);
?>

output
my name is anllin, my age is 29.
目录句柄操作
opendir -- 打开目录句柄
readdir -- 从目录句柄中读取条目
closedir -- 关闭目录句柄
复制代码 代码如下:
$dir= opendir('../Basic6');
while(!!$file = readdir($dir))
{
echo $file.'
';
}
closedir($dir);
?>

output
.
..
.buildpath
.project
.settings
demo1.php
demo10.php
demo11.php
demo12.php
demo13.php
demo14.php
demo15.php
demo16.php
demo17.php
demo18.php
demo19.php
demo2.php
demo20.php
demo3.php
demo4.php
demo5.php
demo6.php
demo7.php
demo8.php
demo9.php
file1.txt
file2.txt
scandir -- 列出指定路径中的文件和目录
复制代码 代码如下:
$files = scandir('../Basic6');
foreach($files as $file)
{
echo $file.'
';
}
?>

output
.
..
.buildpath
.project
.settings
demo1.php
demo10.php
demo11.php
demo12.php
demo13.php
demo14.php
demo15.php
demo16.php
demo17.php
demo18.php
demo19.php
demo2.php
demo20.php
demo21.php
demo3.php
demo4.php
demo5.php
demo6.php
demo7.php
demo8.php
demo9.php
file1.txt
file2.txt
rename -- 重命名一个文件或目录
复制代码 代码如下:
rename('demo1.php','demo01.php');
if(file_exists('demo01.php'))
{
echo 'file rename success';
}
else
{
echo 'file rename fail';
}
?>

output
file rename success
rmdir -- 删除目录
复制代码 代码如下:
rmdir('123');
if(file_exists('123'))
{
echo 'delete file fail';
}
{
echo 'delete file success';
}
?>

output
delete file success
Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools