PHP create file and write file

PHP File Create and Write

In this PHP tutorial we will learn how to create a file and how to write to a file on the server.

  • Create a File – touch() ,
  • Create a File, if does not exist – fopen()
  • Write to a File – fwrite()

PHP – Create a File

The touch() function is used to create a file on server. The fopen() function is also used to create a file in PHP. If we use fopen() function on a file the file does not exist, then it will create it. The touch() function and fopen() work same for creating a file on server where the php file directory code.

The PHP touch() function Syntax :


touch(“filename with extension”);


PHP touch() function example

Here we use PHP touch() function to create a new file called ‘abc.txt’, ‘abc.doc’ and ‘abc.pdf’ on server.

When run above php code the file abc.txt, abc.pdf and abc.doc will be created in PHP program folder.

PHP fopen() function

When we use fopen() function for creating a new file, must assign mode character with function (w) for writing mode or (a) for appending mode.

fopen() syntax :


fopen(“filename with extension”, “mode char”);


Example of fopen() function

The fopen() function has following modes :

  • w = write only. if file exist open it, if not then create a new file.
  • w+ = read/write
  • r = read only
  • r += read / write
  • a = append file
  • a+ = read / append
  • x = write only. create new file, returns error if file already exists.
  • x+ = read/write.

PHP fwrite() Function

The PHP fwrite() function is used to write to a file means write contents inside the file.

PHP  fwrite() syntax


fwrite(“filename”,”text to be written”);


The fwrite() function has first parameter is file name and the second parameter is text to be written in file.

fwrite() function example

For write context to file we must use fopen() function to open the file and then use fwrite() function for write to file.

The output is : when we open abc.txt file it has content like : “Meera Academy”. Here, we first open the file abc.txt and write some text using fwrite() function and then finally close the file using fclose() function.

PHP form example of fwrite()

The output is :

PHP file handling functions

PHP file handling example


Leave a Reply

Your email address will not be published. Required fields are marked *

Captcha *