Php file writing function instance program

Source: Internet
Author: User

Method 1: Using fopen and fwirte functions

1. How to open a file in PHP

Use the PHP function fopen () to open a file. fopen () usually uses two parameters to indicate the path and file mode for opening the file. For example:

The code is as follows: Copy code
$ Fp = fopen ("../cnbruce.txt", 'w ');


Specifically, "../cnbruce.txt" indicates the path of the cnbruce.txt File (relative to the path of the current execution program file), and 'W' indicates opening the text file in write-only mode.

For file writing

Fwrite (file, string, length)

Parameter description:

File is required. Specifies the open file to be written.

String is required. Specifies the string of the file to be written.

Length is optional. Specifies the maximum number of bytes to write.


The code is as follows: Copy code

* File writing functions
* @ Param string $ filename file name
* @ Param string $ text the text string to be written
* @ Param string $ openmod text writing mode ('w': overwrite, 'A': text append)
* @ Return boolean
Function write_file ($ filename, $ text, $ openmod = 'w '){
If (@ $ fp = fopen ($ filename, $ openmod )){
Flock ($ fp, 2 );
Fwrite ($ fp, $ text );
Fclose ($ fp );
Return true;
} Else {
Return false;

Method 2: Use file_put_contents to implement read/write

The file_put_contents function has a very useful parameter LOCK_EX. After it is added, no content is missing.

This parameter LOCK_EX is straightforward, that is, when writing a file, first lock the file, so that only a client can access the write, other clients can not access the write.

My usage is as follows:

The code is as follows: Copy code

File_put_contents ($ file, $ content, FILE_APPEND | LOCK_EX)


$ File => This is the path of the written file + file name.
$ Content => This is the content of the written file.
FILE_APPEND => directly append content to the existing content of the file
LOCK_EX => lock when writing files to prevent content loss caused by simultaneous writing by multiple users

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.