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");
?>

Tools:

Crypto Currency

PHPKIDA provides free online the best real-time crypto market price, news, predictions, index with graphs & historical data for 2000+ coins including bitcoin, ethereum, & altcoins from major cryptocurrency exchanges.

Visite Tool

Icon Generator

PHPKIDA provides free online icon generator. Our icon generator help you to edit, modify, resize and customize icon for your website and applications. Convert to a shap you like add icon border, you can change icon border color, border size, background color, icon shadow, icons color, icon size in your own way and save it as a png image.

Visite Tool

Youtube Video Downloader

PHPKIDA provides Free online YouTube video downloader to download YouTube videos quickly in MP4, 3GP, and more. Search your video and free fast download youtube videos.

Visite Tool

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.