In this tutorials, we are going to see how to write content on a file in php.

PHP fwrite :

php fwrite is a function which is used to write a content on file. To write content on file, first of all we need to create a file and open it. We have discussed in previous tutorials how to open a file and operations on file in php.

fopen(location) is a function which is used to open a file in given location. If the file doesn’t exist in the given location, it will create the file and opens it.


$file = fopen("/home/chandrashekhar/Desktop/MyFile.txt", "w") or die("Unble to open the file ");


The file uses “w” to create a writeable file. Before you can write, PHP needs to have the permission to write to disk.

PHP fwrite Example :

This function is used to write to a specified file. We shall create a file called MyFile.txt


$file = fopen("/home/chandrashekhar/Desktop/Sample.txt", "w") or die("Unble to open the file ");
$content = "PHP fwrite example Tutorials";
fwrite($file, $content);

The above example creates a file (Sample.txt) on my Desktop and writes the content on the Sample.txt file.

PHP fwrite example Tutorials

Happy Learning 🙂