Latest web development tutorials

PHP file_put_contents () function

PHP Filesystem Reference Manual Complete PHP Filesystem Reference Manual

Definition and Usage

file_put_contents () function takes a string to the file.

The function to access the file, follow these rules:

  1. If the FILE_USE_INCLUDE_PATH, then checks the * filename * Built-copy path
  2. If the file does not exist, create a file
  3. open a file
  4. If the LOCK_EX, then the lock file
  5. If the FILE_APPEND, it will be moved to the end of the file. Otherwise, it will clear the contents of the file
  6. Write data to a 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.

grammar

file_put_contents(file,data,mode,context)

参数 描述
file 必需。规定要写入数据的文件。如果文件不存在,则创建一个新文件。
data 必需。规定要写入文件的数据。可以是字符串、数组或数据流。
mode 可选。规定如何打开/写入文件。可能的值:
  • FILE_USE_INCLUDE_PATH
  • FILE_APPEND
  • LOCK_EX
context 可选。规定文件句柄的环境。context 是一套可以修改流的行为的选项。


Tips and Notes

NOTE: Use FILE_APPEND avoid deleting files that already exist in the content.


Examples

<?php
echo file_put_contents("test.txt","Hello World. Testing!");
?>

The code above will output:

21


PHP Filesystem Reference Manual Complete PHP Filesystem Reference Manual