PHP File Handling

PHP File Handling

The PHP’s file system functions are used to create, open, read and write files.

You already know PHP is a server side programming language, it allows you to work with files and directories stored on the web server. In this tutorial you will learn how to create, open, read, and write files and directory on your web server using the PHP file system functions.

You will learn following functions related to files handling:

  • Opening a file fopen()
  • Reading a file fread()
  • Writing a file fwrite()
  • Closing a file fclose()

Opening and Closing Files

The PHP fopen() function is used to open a file. It requires two arguments first the file name and second is mode in which to operate. Files modes can be specified as one of the six options in this below table.

ModePurpose
rOpens 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.
wOpens 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.
aOpens 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 fopen() function fails to open a file it returns false and generate an warning message. So you should implement a simple check whether the file exists or not before trying to access it.

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.

Syntax of fopen() function

  fopen(filename, mode)

Example of fopen() function

   $myfile = fopen("test.txt", "r");

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 you can follow the following 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.

Just you can try this example, the following example assigns the content of a text file to a $filetext variable then displays those contents on the web page.

<?php
         $filename = "test.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;
 ?>

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.

Example of creates a new text file then writes text inside it. After closing this file we are checking file is exist or not using file_exist() function which takes file name as an argument.

<?php
$filename = "test.txt";
   $file = fopen( $filename, "w" );
   
   if( $file == false ) {
      echo ( "Error in opening new file" );
      exit();
   }
   fwrite( $file, "This is  a simple test file\n" );
   fclose( $file );
?>
<?php
         $filename = "test.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 is: $filename");
?>

PHPKIDA Offering Free Tools:

INSTA DOWNLOADER

Free online tool to download Instagram videos, photos and save Instagram videos, photos to your device. It's free & easy to use.

Download Now

CURRENCY CONVERTER

Our real time currency converter calculator will convert your money based on current values from around the world. It's free & easy to use.

Convert Now

ROBOST.TXT GEN.

Create robots txt file that help search engines to crawling and indexing your site with help of our free online Robots.txt Generator tool.

Create Now

HTML MINIFIER

Free online tool to minify or compress html code and reduce the size of html code in few clicks. It's free & easy to use.

Minify Now

CSS MINIFIER

Free online tool to minify or compress css code and reduce the size of css code in few clicks. It's free & easy to use.

Minify Now

JAVASCRIPT MINIFIER

Free online tool to minify or compress javascript code and reduce the size of javascript code in few clicks. It's free & easy to use.

Minify Now

Sign up for weekly update

Milkshake is almost ready. If you're interested in testing it out, then sign up below to get exclusive access.