Read and Write text file in PHP

In many Websites we develop, most of them use the log system so we can map system points to be analyzed later, such as a connection failure, attempts to access a restricted place … Anyway there are many possibilities of use a log file.

For this we will use only three functions, which is the fopen to open the file, fwrite to write to the file, and fclose to close the file.

The first step is to define the name of the file in which we will do read write operations (or what is the name of file to be created), in our example will specify a suggestive name like “file.txt” and add it to a variable “$file”.

In our example we will insert the text “Hello. is awesome website for freshers ” for this we create  variable “$text” .

As your system already know the file name, use the function fopen inform the file to open, and so that it will open.

As you can se we are using a second parameter in our fopen function with value “a”. With this parameter we are   telling the system to open our file, in which case, it will open up and prepare it for writing , and if the file does not exist the system will create it. See other options in the PHP documentation

NOTE : If the file does not exist on your server, and the folder where it will be written is not writable or have permission to write , it may result in the error “Failed to open stream: Permission denied in …” to resolve this, create the file manually, and give written permission or give written permission to the folder where you have created the file.

Once the file open it is  time to write something in it, we will use the function fwrite for this,  this function informs the file which file is to be opened and what to write in it.

Mission accomplished, now it is  good practice everything you use  you must guard it also, then as we have opened  the file, now time to close the file  … This will prevent the file to be corrupted after writing .
In this case we will use the fclose  function informing the file to be closed.

The full code is as follows .

Add this code in index.php and create a file.txt on the same directory and run it .

An example of this use is to record log that POST variable returns , see below how you would capture the posts.


Leave a Reply

Your email address will not be published. Required fields are marked *