English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic PHP Tutorial

Advanced PHP Tutorial

PHP & MySQL

PHP Reference Manual

Usage and examples of PHP file_put_contents() function

PHP Filesystem Reference Manual

The file_put_contents() function can write a string to the file.

Syntax

int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ] ] )

The following rules are followed when the function accesses the file:

  1. If FILE_USE_INCLUDE_PATH is set, it will check *filename* built-in path of the copy

  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 content of the file will be cleared

  6. Write data to the file

  7. 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

ParametersDescription
fileRequired. Specify the file to write the data to. If the file does not exist, a new file will be created.
dataRequired. Specify the data to be written to the file. It can be a string, an array, or a data stream.
modeOptional. Specify how to open/Writing to the file. Possible values:
  • FILE_USE_INCLUDE_PATH

  • FILE_APPEND

  • LOCK_EX

contextOptional. Specify the file handle environment. Context is a set of options that can modify the behavior of the stream.

Example1

Write content to the file sample.txt

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

Output Result

11

Example2

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.

PHP Filesystem Reference Manual