PHP file_put_contents() function

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

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

The output produced by the above PHP example on the 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 the opened file myfile.txt, after executing the above PHP example:

php file_put_contents function

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

Note: If the specified file does not exist, then a new file will be created.

PHP file_put_contents() Syntax

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

file_put_contents(file, data, mode, context)

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

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 or write 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 in which to handle the file.

PHP file_put_contents() example

Consider the following PHP code as an example demonstrating the "file_put_contents()" function:

<?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 the above PHP example is:

php file put contents example

Now let me create another example, with FILE_APPEND as the value of the 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 the previous one after executing this example. And here is the snapshot of the file, myfile.txt, after executing the previous two PHP examples:

php file put contents function example

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!