English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
PHP Filesystem Reference Manual
The file_put_contents() function can write a string to the file.
int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ] ] )
The following rules are followed when the function accesses the file:
If FILE_USE_INCLUDE_PATH is set, it will check *filename* built-in path of the copy
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 content of the file will be cleared
Write data to the file
Close the file and unlock all files
If successful, the function can return the number of characters written to the file. If it fails, it can return false.
Parameters | Description |
---|---|
file | Required. Specify the file to write the data to. If the file does not exist, a new file will be created. |
data | Required. Specify the data to be written to the file. It can be a string, an array, or a data stream. |
mode | Optional. Specify how to open/Writing to the file. Possible values:
|
context | Optional. Specify the file handle environment. Context is a set of options that can modify the behavior of the stream. |
Write content to the file sample.txt
<?php echo file_put_contents("sample.txt", "Hello World!"); ?>
Output Result
11
Use FILE_APPEND to append content, to avoid deleting the existing content in the file.
<?php $file = "sample.txt"; //new user to be added to the file $test = " w3codebox"; //Use the FILE_APPEND flag to append content to the end of the file //and the LOCK_EX flag to prevent anyone else from writing to the file at the same time file_put_contents($file, $test, FILE_APPEND | LOCK_EX); echo "The content has been successfully appended and written to the file."; ?>
Output Result
The content has been successfully appended and written to the file.