PHP file_put_contents() Function
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 these rules:
- If FILE_USE_INCLUDE_PATH is set, check the filename built-in path of the copy
- If the file does not exist, create a file
- Opening a File
- If LOCK_EX is set, lock the file
- If FILE_APPEND is set, move to the end of the file. Otherwise, the file contents are cleared
- Write the data to the file
- Close the file and unlock all files
Returns the number of characters written to the file on success, or FALSE on failure.
Syntax
int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )
| Parameters | 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, an array, or a stream. |
| flags | Optional. Specifies how to open/write the file. Possible values:
|
Tips and Notes
**Note:** Use FILE_APPEND to avoid deleting the existing contents of the file.
Example
Example
The output of the above example is:
6
Next, we append content to the file sites.txt:
Example
After successful execution, open sites.txt; its content is:
Runoob
Google