PHP file_put_contents()Functions
Complete PHP Filesystem Reference Manual
Definition and Usage
The file_put_contents() function writes a string to a file.
When accessing a file, this function follows the following rules:
- If FILE_USE_INCLUDE_PATH is set, the built-in path of the *filename* copy will be checked
- If the file does not exist, a file will be created
- Open the file
- If LOCK_EX is set, the file will be locked
- If FILE_APPEND is set, it will move to the end of the file. Otherwise, the file contents will be cleared
- Write data to the file
- Close the file and unlock all files
If successful, the function returns the number of characters written to the file. If it fails, it returns False.
Syntax
int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )
| Parameter | Description |
|---|---|
| filename | Required. Specifies the file to write data to. If the file does not exist, a new file is created. |
| data | Required. Specifies the data to write to the file. Can be a string, array, or data stream. |
| flags | Optional. Specifies how to open/write the file. Possible values:
|
| context | Optional. Specifies the environment of the file handle. context is a set of options that can modify the behavior of the stream. |
Tips and Notes
Note:Use FILE_APPEND to avoid deleting existing content in the file.
Example
Example
echo file_put_contents("sites.txt","Example");
The output of the above example is:
6
Next, we append content to the file sites.txt:
Example
$file = 'sites.txt';
$site = "\nGoogle";
//Append content to a file
//Using the FILE_APPEND flag, content can be appended to the end of the file
//The LOCK_EX flag can prevent multiple people from writing at the same time
file_put_contents($file, $site, FILE_APPEND | LOCK_EX);
After successful execution, open the sites.txt file, the content is:
Example Google
Other Extensions