PHP File Create/Write

In this chapter we will see how we can create a new file and if we want to write something in this file then how we can do that.

fopen() Function in PHP

fopen() function is basically used to open a file but in case file doesn’t exists then it will create a new file with the name defined as filename argument in the fopen() function.

Syntax of fopen() function in PHP

In the filename parameter, we need to specify the filename which we want to open or create.

And in the filemode parameter, we need to specify in which more we want to open that particular file. There are mainly six file modes in PHP which can be used here as parameter.

PHP File Modes
Mode Purpose
r This specify that the file is for read only purpose.

And the file pointer will be placed at the beginning of the file.

r+ This specify that the file is for read and write both purposes.

And the file pointer will be placed at the beginning of the file.

w This specify that the file is for write only purpose. And If files does not exist then it will create a new file.

And the file pointer will be placed at the beginning of the file.

w+ This specify that the file is for read and write both purposes. And If files does not exist then it will create a new file.

And the file pointer will be placed at the beginning of the file.

a This specify that the file is for write purposes. And If files does not exist then it will create a new file.

And the file pointer will be placed at the end of the file.

a+ This specify that the file is for read and write both purposes. And If files does not exist then it will create a new file.

And the file pointer will be placed at the end of the file.

Example of fopen() function in PHP

Now if you will open the file,  then you will find the text in the file which we write using the fwrite() function.

 

Leave a Reply

Your email address will not be published.