PHP file_put_contents()Functions


PHP Filesystem 参考手册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:

  1. If FILE_USE_INCLUDE_PATH is set, the built-in path of the *filename* copy will be checked
  2. If the file does not exist, a file will be created
  3. Open the file
  4. If LOCK_EX is set, the file will be locked
  5. If FILE_APPEND is set, it will move to the end of the file. Otherwise, the file contents will be cleared
  6. Write data to the file
  7. 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:
  • FILE_USE_INCLUDE_PATH
  • FILE_APPEND
  • LOCK_EX
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

<?php 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

<?php $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


PHP Filesystem 参考手册Complete PHP Filesystem Reference Manual

Other Extensions