251 of 410 menu

The file_put_contents Function

The file_put_contents function writes data to a file. The first parameter is the path to the file, the second is the data to write. The third optional parameter defines the write mode (see the table below).

The fourth optional parameter is a stream context resource created by the stream_context_create function. It allows configuring parameters for working with a file or network resource.

Syntax

file_put_contents( string $filename, mixed $data, int $flags = 0, ?resource $context = null ): int|false

Values of the Third Parameter

Flag Description
FILE_USE_INCLUDE_PATH If set, the function will search for the file in the directories specified in the include_path parameter of the PHP settings in the php.ini file.
FILE_APPEND Append data to the end of the file instead of overwriting
LOCK_EX Obtain an exclusive lock on the file during writing

Example

Let's write a string to a file:

<?php $res = file_put_contents('data.txt', 'abcde'); echo $res; ?>

The result of code execution returns the number of bytes written:

5

Example

Let's append data to the end of the file:

<?php $res = file_put_contents('data.txt', '12345', FILE_APPEND); echo $res; ?>

Example

Writing an array to a file:

<?php $data = ['a', 'b', 'c']; $res = file_put_contents('array.txt', implode(',', $data)); echo $res; ?>

Example

In the third parameter, you can specify several flags by listing them with the | symbol. As an example, let's append data with file locking:

<?php $res = file_put_contents( 'log.txt', "text", FILE_APPEND | LOCK_EX ); echo $res; ?>

Example

Using context:

<?php $opts = [ 'http' => [ 'method' => "POST", 'header' => "Content-type: text/plain\r\n" ] ]; $context = stream_context_create($opts); $res = file_put_contents( 'http://example.com/api', 'data=test', false, $context ); ?>

See Also

  • the file_get_contents function,
    which reads the contents of a file
  • the fopen function,
    which opens a file
  • the fwrite function,
    which writes to a file
byenru