search
HomeBackend DevelopmentPHP TutorialPHP文件操作实现代码分享_PHP

将数据写或读入文件,基本上分为三个步骤:
1. 打开一个文件(如果存在)
2. 写/读文件
3. 关闭这个文件
l打开文件
在打开文件文件之前,我们需要知道这个文件的路径,以及此文件是否存在。
用$_SERVER[“DOCUMENT_ROOT”]内置全局变量,来获得站点的相对路径。如下:
$root = $_SERVER[“DOCUMENT_ROOT”];
在用函数file_exists()来检测文件是否存在。如下:
If(!file_exists("$root/order.txt")){echo ‘文件不存在';}
接下来用fopen()函数打开这个文件。
$fp = fopen("$root/order.txt",'ab');
fopen()函数,接受2个或3个或4个参数。
第一个参数为文件路径,第二个为操作方式(读/写/追加等等),必选参数。
$fp = fopen("$root/order.txt",'ab');
第三个为可选参数,如果需要PHP在include_path中搜索一个文件,就可以使用它,不需要提供目录名或路径。
$fp = fopen("order.txt",'ab',true);
第四个也为可选参数,允许文件名称以协议名称开始(如http://)并且在一个远程的位置打开这个文件,也支持一些其他的协议,比如ftp等等。
如果fopen()成功的打开一个文件,就返回一个指向此文件的指针。在上面我们保存到了$fp变量中。

附文件模式图


写文件
在PHP中写文件比较简单。直接用fwrite()函数即可。
fwrite()的原型如下

int fwrite(resource handle,string string [,int length]);

第三个参数是可选的,表明写入文件的最大长度。
可以通过内置strlen()函数获得字符串的长度,如下:

fwrite($fp,$outputinfo,strlen($outputinfo));

此函数告诉PHP将$outputinfo中的信息保存到$fp指向的文件中。
l读文件
1. 以只读模式打开文件
仍然使用fopen()函数,但只读模式打开文件,就用“rb”文件模式。如下:

$fp = fopen(“$root/order.txt”,'rb');
2. 知道何时读完文件
我们用while循环来读取文件内容,用feof()函数,作为循环条件的终止条件。如下:

while(!feof($fp)){
//要处理的信息
}
3.每次读取一行记录
fgets()函数可以从文本文件中读取一行内容。如下:
复制代码 代码如下:
$fp = fopen("$root/order.txt",'rb');
while(!feof($fp)){
$info = fgets($fp,999);
echo $info.'
';
}
fclose($fp);

这样,他将不断的读入数据,直到读取一个换行符(\n)或者文件结束符EOF,或者是从文件中读取了998B,可以读取的最大长度为指定的长度减去1B。
4.读取整个文件
PHP提供了4中不同的方式来读取整个文件。
a).readfile()函数
它可以不用先fopen($path)文件和关闭文件,也不用echo,直接使用即可。如下:
readfile(“$root/order.txt”);
它会自动把文件的信息,输出到浏览器中。它的原型如下:
Int readfile(string filename,[int use_include_path[,resource context]]);
第二个可选参数指定了PHP是否在include_path中查找文件,这一点于fopen函数一样,返回值为从文件中读取的字节总数。
注:直接使用,不用fopen或fclose
b).fpassthru()函数
要使用这个函数,必须先fopen()打开一个文件。然后将文件的指针作为参数传递给fpassthru(),这样就可以把文件指针所指向的文件内容输出。然后再将这个文件关闭。如下:
$fp = fopen(“$root/order.txt”,'rb');
fpassthru($fp);
fclose($fp);
返回值同样为从文件中读取的字节总数。
注:必须fopen和fclose
c).file()函数
除了将文件输出到浏览器中外,他和readfile()函数是一样的,它把结果发送到一个数组中。如下:
$fileArray = file(“$root/order.txt”);
文件中的每一行,将作为数组的每一个元素。
注:直接使用,不用fopen和fclose
d).file_get_contents()函数
于readfile()相同,但是该函数将以字符串的形式返回文件内容,而不是将文件内容直接输出到浏览器中,也就是必须使用echo 输出,如下:

echo file_get_contents(“$root/order.txt”);
注:直接使用,不用fopen和fclose
5.读取一个字符
fgetc()函数从一个文件中一次读取一个字符,它具有一个文件指针函数,这也是唯一的参数,而且它返回下一个字符。如下:
复制代码 代码如下:
$fp = fopen("$root/order.txt",'rb');
while(!feof($fp)){
$char = fgetc($fp);
if(!feof($fp)){
echo ($char == "\n" ? '
' : $char);
}
}
fclose($fp);

注:fgetc()函数的一个缺点就是它返回文件的结束符EOF,而fgets()则不会。读取字符后还需要判断feof()。
6. 读取任意长度
fread()函数即为从文件中读取任一长度的字节,函数原型如下:

string fread(resource fp,int length);
使用该函数时,它或者是读满了length参数所指定的字节数,或者是读到了文件的结束。
复制代码 代码如下:
$fp = fopen("$root/order.txt",'rb');
echo fread($fp,10); //读取10个字节
fclose($fp);

l关闭文件
关闭文件比较简单,直接调用fclose()函数即可,如果返回true,则表明成功,反之。如下:

fclose($fp);
l删除文件
unlink()函数(没有名为delete的函数),如下:

unlink("$root/order.txt");
l确定文件大小
可以使用filesize()函数来查看一个文件的大小(字节为单位),如下:
echo filesize("$root/order.txt");

大家也可以参考下面的文章
以下是一篇关于文件基本读写操作的文章,我曾经就是看了这篇文章后学会文件基本操作的,在这里发出来与大家共享:
读文件:
PHP代码:
复制代码 代码如下:
1. 2.  
3. $file_name = "data.dat";
4. // 要读取的文件的绝对路径: homedata.dat
5.  
6. $file_pointer = fopen($file_name, "r");
7. // 打开文件,8. "r" 是一种模式,9. 或者说我们要进行的操作方法,10. 详见本文后面的介绍
11.  
12. $file_read = fread($file_pointer, filesize($file_name));
13. // 通过文件指14. 针读取文件内容
15.  
16. fclose($file_pointer);
17. // 关闭文件
18.  
19. print "读取到的文件内容是: $file_read";
20. // 显示文件内容
21. ?>
22.  

写文件:
PHP代码:
复制代码 代码如下:
1. 2.  
3. $file_name = "data.dat";
4. // 绝对路径: homedata.dat
5.  
6. $file_pointer = fopen($file_name, "w");
7. // "w"是一种模式,8. 详见后面
9.  
10. fwrite($file_pointer, "what you wanna write");
11. // 先把文件剪切12. 为0字节大小,13. 然后写入
14.  
15. fclose($file_pointer);
16. // 结束
17.  
18. print "数据成功写入文件";
19.  
20. ?>
21.  

追加到文件后面:
PHP代码:
复制代码 代码如下:
1. 2.  
3. $file_name = "data.dat";
4. // 绝对路径: homedata.dat
5.  
6. $file_pointer = fopen($file_name, "a");
7. // "w"模式
8.  
9. fwrite($file_pointer, "what you wanna append");
10. // 不11. 把文件剪切12. 成0字节,13. 把数据追加到文件最后
14.  
15. fclose($file_pointer);
16. // 结束
17.  
18. print "数据成功追加到文件";
19.  
20. ?>
21.  

以上只是简单介绍,下面我们要讨论一些更深层的。
有时候会发生多人写入的情况(最常见是在流量较大的网站),会产生无用的数据写入文件, 例如:
info.file文件内容如下 ->
|1|Mukul|15|Male|India (n)
|2|Linus|31|Male|Finland (n)
现在两个人同时注册,引起文件破坏->
info.file ->
|1|Mukul|15|Male|India
|2|Linus|31|Male|Finland
|3|Rob|27|Male|USA|
Bill|29|Male|USA
上例中当PHP写入Rob的信息到文件的时候,Bill正好也开始写入,这时候正好需要写入Rob纪录的'n',引起文件破坏。
我们当然不希望发生这样的情况, 所以让我们看看文件锁定:
PHP代码:
复制代码 代码如下:
1. 2.  
3. $file_name = "data.dat";
4.  
5. $file_pointer = fopen($file_name, "r");
6.  
7. $lock = flock($file_pointer, LOCK_SH);
8. // 我使用4.0.2,9. 所以用LOCK_SH,10. 你可能需要直接写成 1.
11.  
12. if ($lock) {
13.  
14. $file_read = fread($file_pointer, filesize($file_name));
15. $lock = flock($file_pointer, LOCK_UN);
16. // 如果版本小于PHP4.0.2,17. 用 3 代替 LOCK_UN
18.  
19. }
20.  
21. fclose($file_pointer);
22.  
23. print "文件内容为 $file_read";
24.  
25. ?>
26.  

上例中,如果两个文件read.php和read2.php都要存取该文件,那么它们都可以读取,但是当一个程序需要写入的时候,它必须等待,直到读操作完成,文件所释放。
PHP代码:
复制代码 代码如下:
1. 2.  
3. $file_name = "data.dat";
4.  
5. $file_pointer = fopen($file_name, "w");
6.  
7. $lock = flock($file_pointer, LOCK_EX);
8. // 如果版本低于PHP4.0.2,9. 用 2 代替 LOCK_EX
10.  
11. if ($lock) {
12.  
13. fwrite($file_pointer, "what u wanna write");
14. flock($file_pointer, LOCK_UN);
15. // 如果版本低于PHP4.0.2,16. 用 3 代替 LOCK_UN
17.  
18. }
19.  
20. fclose($file_pointer);
21.  
22. print "数据成功写入文件";
23.  
24. ?>
25.  

虽然"w"模式用来覆盖文件, 单我觉得不适用。
PHP代码:
复制代码 代码如下:
1. 2.  
3. $file_name = "data.dat";
4.  
5. $file_pointer = fopen($file_name, "a");
6.  
7. $lock = flock($file_pointer, LOCK_EX);
8. // 如果版本低于PHP4.0.2,9. 用 2 代替 LOCK_EX
10.  
11. if ($lock) {
12.  
13. fseek($file_pointer, 0, SEEK_END);
14. // 如果版本小于PHP4.0RC1,15. 使用 fseek($file_pointer, filsize($file_name));
16.  
17. fwrite($file_pointer, "what u wanna write");
18. flock($file_pointer, LOCK_UN);
19. // 如果版本低于PHP4.0.2,20. 用 3 代替 LOCK_UN
21.  
22. }
23.  
24. fclose($file_pointer);
25.  
26. print "数据成功写入文件";
27.  
28. ?>
29.  

Hmmm..., 对于追加数据与其他操作有点不同,就是FSEEK! 确认文件指针在文件尾部总是一个好习惯。
如果是在Windows系统下, 上面的文件中文件名前面需要加上''.
FLOCK杂谈:
Flock()只在文件打开后才锁定。 在上列中文件打开后才获得锁定,现在文件的内容只是在当时的内容, 而不反映出别的程序操作的结果,因此不只是在文件追加操作,就是对读取操作也应该使用fseek。
(此处翻译可能不是很确切, 但我想意思到了)。
关于模式:
'r' - 只读方式打开, 文件指针置于文件头
'r+' - 读写方式打开,文件指针置于文件头
'w' - 只写打开,文件指针置于文件头, 文件被剪切为0字节, 如果文件不存在, 尝试建立文件
'w+' - 读写打开,文件指针置于文件头, 文件大小被剪切为0字节,如果文件不存在, 尝试建立文件
'a' - 只写方式打开,文件指针置于文件尾,如果文件不存在,尝试建立文件
'a+' - 读写打开,文件指针置于文件尾,如果文件不存在, 尝试建立文件
顺便说一下创建文件目录的代码
复制代码 代码如下:
//创建类似"../../../xxx/xxx.txt"的目录
function createdirs($path, $mode = 0777) //mode 077
{
$dirs = explode('/',$path);
$pos = strrpos($path, ".");
if ($pos === false) { // note: three equal signs
// not found, means path ends in a dir not file
$subamount=0;
}
else {
$subamount=1;
}
for ($c=0;$c $thispath="";
for ($cc=0; $cc $thispath.=$dirs[$cc].'/';
}
if (!file_exists($thispath)) {
//print "$thispath";
mkdir($thispath,$mode); //mkdir函数创建目录
}
}
}
//调用如createdirs("xxx/xxxx/xxxx",);
//原函数中使用$GLOBALS["dirseparator"]我改成了'/'
function recur_mkdirs($path, $mode = 0777) //mode 0777
{
//$GLOBALS["dirseparator"]
$dirs = explode($GLOBALS["dirseparator"],$path);
$pos = strrpos($path, ".");
if ($pos === false) { // note: three equal signs
// not found, means path ends in a dir not file
$subamount=0;
}
else {
$subamount=1;
}

这些只是一些基本的关于文件的操作代码,相信对初学者很有用,在此贴出来,希望有抛砖引玉之功能!

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software