PHP File Create/Write

FILE CREATE /WRITE/CLOSE COMMAND USING PHP

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.

For Example:

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.

For Example:

fwrite(filename, contents);

3. FILE CLOSE (fclose): It is used to close an open file.

For 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

<?php

//file is open using fopen function in a write mode
$file = 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($file, $matter);
$matter = “what is HTML.\n”;
fwrite($file, $matter);

// close an open file
fclose($file);

?>

Result:

php-createwrite




Leave a Reply

avatar
  Subscribe  
Notify of