Writing into a file in php
How to write in to file using php?
Explanation
For testing purpose we have a file
./test1.txt with read, write permissions
Step 1:We will open a stream (connection) with the file using the php method or function
fopen('filename','type')Example:
$open = fopen("./test1.txt", "w");The method fopen takes two arguments, first the file name and second argument that determines the file opening mode. To write in to a file it should be 'w'.
Note:- This method will create a new file if file does not exist.
- It will overwrite the contents in the file if it exists
Step 2:Now we can write in to the file using the method
fwrite()Example:
fwrite($open, "Any thing to be written");This method takes two arguments. First the stream to file obtained as in step1. Second the content to be written. We can call as many write statements as required before closing the stream.
Step 3:After writing in the file we can close the stream opened on the file using the function
fclose()Example:
fclose($open);The function fclose() takes the stream to be closed as an argument and closes the stream.
Example Code:
<?php
$file = "./test1.txt";
$open = fopen($file, "w");
fwrite($open,"Hai this is test message");
?>
The Result : view the file
test1.txtNote: For writing in (next) new lines use n.
Example: "Test n Message" will be written as
Text
Message