file handling in php

Sharing is caring!

This chapter will explain following functions related to files −

  • Opening a file
  • Reading a file
  • Writing a file
  • Closing a file

Opening and Closing Files

The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and then mode in which to operate.

Files modes can be specified as one of the six options in this table.

Mode Purpose
r Opens the file for reading only.

Places the file pointer at the beginning of the file.

r Opens the file for reading and writing.

Places the file pointer at the beginning of the file.

w Opens the file for writing only.

Places the file pointer at the beginning of the file.

and truncates the file to zero length. If files does not

exist then it attempts to create a file.

w Opens the file for reading and writing only.

Places the file pointer at the beginning of the file.

and truncates the file to zero length. If files does not

exist then it attempts to create a file.

a Opens the file for writing only.

Places the file pointer at the end of the file.

If files does not exist then it attempts to create a file.

a Opens the file for reading and writing only.

Places the file pointer at the end of the file.

If files does not exist then it attempts to create a file.

If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file pointer which is used for further reading or writing to that file.

After making a changes to the opened file it is important to close it with the fclose() function. The fclose() function requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails.

Reading a file

Once a file is opened using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes.

The files length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes.

So here are the steps required to read a file with PHP.

  • Open a file using fopen() function.
  • Get the file’s length using filesize() function.
  • Read the file’s content using fread() function.
  • Close the file with fclose() function.

The following example assigns the content of a text file to a variable then displays those contents on the web page.

<html>

   <head>
      <title>Reading a file using PHP</title>
   </head>
   
   <body>
      
      <?php
         $filename = "tmp.txt";
         $file = fopen( $filename, "r" );
         
         if( $file == false ) {
            echo ( "Error in opening file" );
            exit();
         }
         
         $filesize = filesize( $filename );
         $filetext = fread( $file, $filesize );
         fclose( $file );
         
         echo ( "File size : $filesize bytes" );
         echo ( "<pre>$filetext</pre>" );
      ?>
      
   </body>
</html>

It will produce the following result −

Reading File

Writing a file

A new file can be written or text can be appended to an existing file using the PHP fwrite() function. This function requires two arguments specifying a file pointer and the string of data that is to be written. Optionally a third integer argument can be included to specify the length of the data to write. If the third argument is included, writing would will stop after the specified length has been reached.

The following example creates a new text file then writes a short text heading inside it. After closing this file its existence is confirmed using file_exist() function which takes file name as an argument

<?php
   $filename = "/home/user/guest/newfile.txt";
   $file = fopen( $filename, "w" );
   
   if( $file == false ) {
      echo ( "Error in opening new file" );
      exit();
   }
   fwrite( $file, "This is  a simple testn" );
   fclose( $file );
?>
<html>
   
   <head>
      <title>Writing a file using PHP</title>
   </head>
   
   <body>
      
      <?php
         $filename = "newfile.txt";
         $file = fopen( $filename, "r" );
         
         if( $file == false ) {
            echo ( "Error in opening file" );
            exit();
         }
         
         $filesize = filesize( $filename );
         $filetext = fread( $file, $filesize );
         
         fclose( $file );
         
         echo ( "File size : $filesize bytes" );
         echo ( "$filetext" );
         echo("file name: $filename");
      ?>
      
   </body>
</html>

It will produce the following result −

Writing File

 

Comments 7

  • Hey! I realize this is kind of off-topic but I needed to ask. Does running a well-established blog such as yours require a large amount of work? I am brand new to blogging however I do write in my diary on a daily basis. I’d like to start a blog so I can share my own experience and feelings online. Please let me know if you have any kind of recommendations or tips for brand new aspiring blog owners. Thankyou!
    http://educationhints.eu

  • Every weekend i used to go to see this web page, for the reason that i want enjoyment, since this this site conations truly good funny stuff too.
    http://studytip.eu

  • Hi, i think that i saw you visited my blog thus i came to “return the favor”.I’m trying to find things to improve my web site!I suppose its ok to use a few of your ideas!!
    http://financehints.eu

  • I think this is one of the most significant info for me. And i am glad reading your article. But want to remark on few general things, The web site style is wonderful, the articles is really excellent : D. Good job, cheers
    http://educationpoint.eu

  • I delight in, lead to I discovered exactly what I was taking a look for. You’ve ended my four day long hunt! God Bless you man. Have a nice day. Bye

  • Heya! I’m at work browsing your blog from my new iphone 3gs! Just wanted to say I love reading your blog and look forward to all your posts! Carry on the excellent work!

  • Good post. I learn something a lot more challenging on distinct blogs everyday. It’s going to often be stimulating to read content from other writers and practice just a little some thing from their store. I’d prefer to utilize some using the content on my weblog no matter whether you do not mind. Natually I’ll provide you with a link in your net blog.

Leave a Reply

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