Monday , 25 September 2023
Breaking News
Home > Tutorials > PHP > Read and Write Text File with PHP

Read and Write Text File with PHP

This is very common tutorial but peoples who are new in PHP don’t know about PHP file handling functions. Writing on text file and reading back from text file is not difficult task Php provides very good functions for this purpose. I tried my best to make my code simple so let’s start.

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:-

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

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

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.


About Muhammad Faryad

Muhammad Faryad is a professional web application developer. He has been working for 5 years in ICE786 Technologies Pvt. Ltd as a Senior Programmer and Developer. You can contact him on facebook at

Leave a Reply

Ad Test

%d bloggers like this: