We will create two functions
- Write_on_file($file, $message)
- Read_from_file($file)
In first function (Write_on_file) is for writing on text file. It will pass two parameters, one is file name on which text will be written and second is text that will be written on file. Second function (Read_from_file) will only read the file. It passes only one parameter i.e file name. Now see our first function below:-
1 2 3 4 5 6 |
<?php //Function for writing on file function Write_on_file($file, $message) { fwrite(fopen($file, 'a'), $message . "\n"); } ?> |
The above function have two Php built-in functions, 1st is fwrite and 2nd is fopen. fwrite writes on file and fopen opens file for reading in parameters $file is variable that will hold the name of file on which you want to open for writing and $message is variable for holding text that you want to write. Now look at our second function
1 2 3 4 5 6 7 8 |
<?php //Function for reading from file function Read_from_file($file){ $lines = file($file); foreach ($lines as $line_num => $line) { echo $line, '</br>'; }} ?> |
Above function gets the file name and then read it line by line with the help of foreach loop and stores it in $lines variable and then print it with echo function. Now our functions are ready for use. See below codes
1 2 3 4 5 6 7 8 9 10 11 |
<?php $file = 'myfile.txt'; $message = 'It is test message'; //function in action Write_on_file($file,$message); ?> <?php $file = 'myfile.txt'; //function in action Read_from_file($file); ?> |
We have used both functions at a time. $file variable stores the file name and $message variable stores the message or text that you want to write on file. 1st function will write text on file and second function will output on the screen. You can use both functions one by one.
Thanks for reading this post. I hope you like this tutorial. I am waiting for your comments. you can download source code from below link.