在php中文件file_put_contents函数是可以把我们字符串写入到文件中哦,这个与php fwrite文件有一点相同了,下面我来看看看file_put_contents用法与fwrite区别。
PHP file_put_contents() 函数是一次性向文件写入字符串或追加字符串内容的最合适选择。
file_put_contents()
file_put_contents() 函数用于把字符串写入文件,成功返回写入到文件内数据的字节数,失败则返回 FALSE
例子:
代码如下 | 复制代码 |
echo file_put_contents("test.txt", "This is something."); |
运行该例子,浏览器输出:
18
而 test.txt 文件(与程序同目录下)内容则为:This is something.。
提示
•如果文件不存在,则创建文件,相当于fopen()函数行为。
•如果文件存在,默认将清空文件内的内容,可设置 flags 参数值为 FILE_APPEND 以避免(见下)。
•本函数可安全用于二进制对象。
以追加形式写入内容
当设置 flags 参数值为 FILE_APPEND 时,表示在已有文件内容后面追加内容的方式写入新数据:
代码如下 | 复制代码 |
file_put_contents("test.txt", "This is another something.", FILE_APPEND); |
执行程序后,test.txt 文件内容变为:This is something.This is another something.
file_put_contents() 的行为实际上等于依次调用 fopen(),fwrite() 以及 fclose() 功能一样。
那么到底file_put_contents与fwrite区别在哪里
如下为file_put_contents的实例代码:
代码如下 | 复制代码 |
$filename = 'file.txt'; |
同样的功能使用fwrite的实例代码:
代码如下 | 复制代码 |
$filename = 'file.txt'; |
从以上两个例子看出,其实file_put_contents是fopen、fwrite、fclose三合一的简化写法,这对程序代码的优化是有好处的,一方面在代码量上有所减少,另一方面不会出现fclose漏写的不严密代码,在调试、维护上方便很多。
上述例子里,file_put_contents是从头写入,如果要追加写入,怎么办呢?
在file_put_contents的语法里,有个参数FILE_APPEND,这是追加写入的声明。实例代码如下:
代码如下 | 复制代码 |
echo file_put_contents('file.txt', "This is another something.", FILE_APPEND); |
FILE_APPEND就是追加写入的声明。在追加写入时,为了避免其他人同时操作,往往需要锁定文件,这时需要加多一个LOCK_EX的声明,写法如下:
代码如下 | 复制代码 |
echo file_put_contents('file.txt', "This is another something.", FILE_APPEND|LOCK_EX); |
注意,以上代码中echo输出到显示器里的是写入文件字符串的长度

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use
