File handling with PHP

November 29, 2014
by Rahil Shaikh

In this tutorial we will be learning about file handling in php, as we go about this tutorial I’ll be creating a simple application that will write to a file and display the data from the file.

To perform any operation on a file we need to first create a handle, to do so we need the fopen() function of php.

fopen() takes in two parameters , the name of the file for which the handle is begin created and the mode in which the file should be opened.

w-write to a file  eg :- fopen(‘filename’,’w’); – Note ‘w’ mode rewrites the  entire file.

r-read to a file  eg :- fopen(‘filename’,’r’);

a-append to a file  eg :- fopen(‘filename’,’a’);

These are the files I have in the folder . index.php where all the code goes, comments.txt the file on which we will be writing data

File handling directory

Now lets first look at the code.
You can view the demo here – File handling with php demo

<?php
    if(isset($_POST['comment'])) /*Check if the varaible is submited*/
    {
      if(!empty($_POST['comment']))  /*Check for blank data*/
      {
        $comment =  $_POST['comment']; 
        echo 'Click <a href="comments.txt">HERE</a> to view the file <br>'; /*Provide a link to view the file in the browser*/
        $handle = fopen('comments.txt','a');     /*Create a handle for the file and open it in append mode since we want to add to the existing data*/
        fwrite($handle , $comment."n");     /*Writes users comment to the file*/
        fclose($handle);                        /*Closes the handle*/
        echo '<b>Comments</b><br><ul>' ;
        $content = file('comments.txt');       /*Read the file on a line by line basis*/
        foreach($content as $line) {
              echo '<li>'.trim($line).'</li>';  /*Print the contents of the file onto the screen*/
        }
        echo '</ul>';
      }else{
        echo 'please fill in' ;
      }
    }
?>
<form action ="" method ="POST" >
    Add Comment:<br>
    <input type="text" name="comment" ><br><br>
    <input type="submit" value="submit" > <!-- Submit user comment -->
</form>

Although I’ve added inline comments into the code , but we will go through the process step by step.

First the user enters any random comment , and submits it, we then on the php script check if the variable is set and if it is not empty .
Since we want to append to the same file we open the file using the fopen function in append mode (‘a’) .

$handle = fopen(‘comments.txt’,’a’);

Then we write to the file using the fwrite function .

fwrite expects 2 parameters , the file handle and the content to be written.

fwrite($handle , $comment.”n”); (n is used for a line break) .

fclose($handle) closes the file handle.

Now since we want to read the file and print contents  on a line by line basis we use the file() function (instead of fopen() in read mode) and pass the filename to  it.

$content = file(‘comments.txt’); 

Then lastly we use the for each loop to print each comment in the file, to the screen.

In the code above I have have striped off all the styling just to avoid any confusion and of-course our main goal is to provide what matters .
This was just a basic example from me to help you understand how file handling in php works,in actual practice a database would be used for a commenting system and information such as Author,Time etc also needs to be displayed.

 

About

Engineer. Blogger. Thinker. Loves programming and working with emerging tech. We can also talk on Football, Gaming, World Politics, Monetary Systems.

Free PDF

Subscribe and get AngularJS Tips PDF. We never spam!
First Name:
Email:

Leave a Comment