How to Write a File with the PHP file_put_contents() Function

09/04/2021

Contents

In this article, you will learn how to write a file with the PHP file_put_contents() function.

PHP file_put_contents() Function

The file_put_contents() function in PHP can be used to write a string to a file.
The basic syntax is:

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

The first parameter is the name of the file you want to write to, including the path. The second parameter is the string or data you want to write to the file.
Here is an example of writing a string to a file:

<?php
  $data = "Hello, World!";
  file_put_contents("example.txt", $data);
?>

You can also write an array to a file by using json_encode() to convert the array to a JSON string, and then passing that string to file_put_contents():

<?php
  $data = array(1, 2, 3, 4, 5);
  $json = json_encode($data);
  file_put_contents("example.json", $json);
?>

You can also use the FILE_APPEND flag as the third parameter to append data to an existing file instead of overwriting it.

<?php
  file_put_contents("example.txt", "Hello again, World!", FILE_APPEND);
?>

It’s important to keep in mind that this function will create the file if it doesn’t exist, and will overwrite the file if it does exist. If you want to add the content to the existing file, you should use FILE_APPEND flag.

Here are a few more things to keep in mind when using file_put_contents():

  • The function returns the number of bytes written to the file on success, or FALSE on failure. You can use this return value to check if the function was successful or not:

    <?php
      $result = file_put_contents("example.txt", "Hello, World!");
      if ($result === false) {
        echo "There was an error writing to the file.";
      } else {
        echo "The file was written successfully, with $result bytes written.";
      }
    ?>
  • The third parameter, $flags, can be used to specify additional options for the function. In addition to FILE_APPEND, other options include:

    LOCK_EX: Acquires an exclusive lock on the file while writing to it. This prevents other processes from modifying the file at the same time.
    FILE_USE_INCLUDE_PATH: Search for the file in the include path.
    FILE_BINARY: Windows only, treat data as binary.

  • The fourth parameter, $context, is used to specify a context for the function. A context is a set of options that can modify the behavior of the function. For example, you can use a context to write to a file over a network or to use a specific encryption method.

  • If the file does not exist and the parent directory doesn’t have write permission the function will fail. So you have to make sure that the directory where you want to write the file, has the write permission.

You can also use fopen() to write the file in the case where you need more control over the file or want to write the file in a specific way.