PHP file_put_contents()
Function
Complete PHP Filesystem Reference Manual
Definition and Usage
The file_put_contents()
function writes a string to a file.
This function follows these rules when accessing the file:
If FILE_USE_INCLUDE_PATH is set, it will check the include path for a copy of filename
If the file does not exist, it will create a new file
Open the file
If LOCK_EX is set, it will lock the file
If FILE_APPEND is set, it will move to the end of the file. Otherwise, it will clear the file's content
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. It can be a string, array, or data stream. |
flags | Optional. Specifies how to open/write the file. Possible values: FILE_USE_INCLUDE_PATH, FILE_APPEND, LOCK_EX |
context | Optional. Specifies the context 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 the existing content of the file.
Examples
Example 1
<?php
echo file_put_contents("sites.txt","tutorialpro");
?>
The output of the above example is:
6
Next, we append content to the file sites.txt:
Example 2
<?php
$file = 'sites.txt';
$site = "\nGoogle";
// Append content to the file
// Use FILE_APPEND flag to append content at the end of the file
// LOCK_EX flag prevents simultaneous writing
file_put_contents($file, $site, FILE_APPEND | LOCK_EX);
?>
After successful execution, open the sites.txt file, the content will be:
tutorialpro
Google