Make PHP Write to File: Use of Fopen and Fwrite Functions

In This Tutorial Developer Guidance (web developer blog) will guide and explain how to create and open a file with fopen() function.

fopen() function is a prdefined function of PHP, it is used for both Create and Open the file. If file does not exists then it will create the file.

PHP fwrite() function is used to write to an opened file. In other words fwrite() function is used to write to a file. The first parameter contain file name to write and second parameter contain is a string to be written (w).

PHP Write To File:

  • PHP fopen() function is used for create and open file.
  • fwrite() PHP function is used to write string of data into the file.
  • Directory must be writable by the web server user for the fopen() function to be able to create a file.

Above example show how to use fopen() function either create file or open the existing file.

fwrite() Method :

fwrite() function in php is used to write a file. fwrite() function is used to write content to a file when a file is already open in write mode.

Append data to a File with PHP

You want to add more students name on student.txt then you need to open the file in append mode. For example

PHP Overwriting

If student.txt file contain some data, we can show, what happen if we open the existing file for writing.All the date will be erased and we start with a empty file.