PHP File Create/Write || PHP Topics

PHP File Create/Write

0 1839


Now, see the PHP functions to create, write and close the file. In which, you can open a new file; you can write content in it and close it safely.

1. FILE CREATE (fopen):

We know that open function is used to open an existing file, but the open function also used to create a new file.

In which we pass two parameters, the first parameter is the name of the file we want to create and second parameter is which mode we want to perform in an existing file.


fopen("filename", "w");
filename: name of the file that need to create
w : writing operation in a file i.e. create a file using w mode.

2. FILE WRITE (fwrite):

In a file we write content using fwrite function. In fwrite function, we pass two parameters, the first parameter is the name of the file which we want to write and the second parameter is the content or matter which we want to write to a file.

These contents are overwriting to an existing file.
Example: fwrite(filename, contents);

3. FILE CLOSE (fclose):

It is used to close an open file.

Example: fclose(filename);

Now come to the coding part..

Step 1: In this example we used a txtfile.txt file. This file is stored in a wamp/www folder.
Step 2: PHP code

//file is open using fopen function in a write mode
= fopen("txtfile.txt", "w") or die ("file doesn't exist");

//$matter is a variable in which contents are defined
$matter = "what is PHP.\n";

//file is write to pass a file name & contents
fwrite(, $matter);
$matter = "what is HTML.\n";
fwrite(, $matter);

// close an open file


Discount Coupons

Leave a Reply

    Waiting for your comments