PHP file_put_contents() Function

The PHP file_put_contents() function is used when we need to write/put some data/content into a file. For example:

<?php
   file_put_contents("myfile.txt", "PHP is Fun! Isn't it?");
?>

The output produced by above PHP example on file_put_contents() function is nothing, but the text PHP is Fun! Isn't it? get written in the file myfile.txt available in the current directory. Here is the snapshot of the current directory along with opened file myfile.txt, after executing the above PHP example:

php file_put_contents function

Note - If the file already have some content, then the previous content gets overwritten with new one. But we can use FILE_APPEND to avoid erasing or overwriting the previous content.

Note - If the specified file does not exists, then a new file will be created.

PHP file_put_contents() Syntax

The syntax of file_put_contents() function in PHP, is:

file_put_contents(file, data, mode, context)

The first two (file and data) parameters are required, whereas the last two (mode and context) parameters are optional.

Note - The file parameter is used to specify the name of the file, in which we need to write the content.

Note - The data parameter is used to specify the data to put into the file.

Note - The mode parameter is used when we need to specify the way to open the file to put/write the data into it. We can specify the way to open the file, in any of the following three ways:

Note - The context parameter is used to specify the context to handle the file.

PHP file_put_contents() Example

<?php
   $file = "myfile.txt";
   $content = "Hey,\nWhat's going on?\nIs everything alright?";
   
   if(file_put_contents($file, $content))
      echo "<p>The content is written into the file.</p>";
   else
      echo "<p>Unable to write the content into the file.</p>";
?>

The output of above PHP example is:

php file put contents example

Now let me create another example, with FILE_APPEND as the value of mode parameter:

<?php
   $file = "myfile.txt";
   $content = "\nYes, everything is Okay.\nThank You!";
   
   if(file_put_contents($file, $content, FILE_APPEND))
      echo "<p>The content is written into the file.</p>";
   else
      echo "<p>Unable to write the content into the file.</p>";
?>

You will get the same output as of previous one, after executing this example. And here is the snapshot of the file, myfile.txt, after executing previous two PHP examples:

php file put contents function example

PHP Online Test


« Previous Tutorial Next Tutorial »