PHP

How to write (PHP fwrite) a file in PHP

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.

<?php

$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

<?php

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

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 :)

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

C Programming

File Handling in C

In this tutorial, we are going to learn about reading and writing files in C. File Handling in C: The English dictionary term file refers to a folder or a…

Ask a question or leave a comment