PHP – File handling Operation

In this tutorial will discuss the various file handling operations and functions.

File handling is the most common operation that a web application can require. Files may be needed to save permanent or temporary data that may require processing by the application. PHP file handling is very user-friendly, which you might not find in other programming languages.

A file is an ordered sequence of bytes stored on a computer hard disk, Memory drive, CD-ROM etc.

A directory holds the names of other files and directories and pointers to their storage area on the media.

A file handle is an integer value used to identify the file to be read or written. Each file in PHP is identified with its handle. If more than one file is open, each file will have a different handle.

PHP file fopen() function

The fopen() function opens files for reading and writing operations, It takes the first argument as a file name you want to open, and it returns a file handle associated with the file.

			

<?php
$file = fopen(“file.txt”,'w');
?>

				

PHP file fread() function

The fread() function is used to read the file after it is opened. It takes two arguments: the first is the file handle, and the second is the number of characters to read.

			

<?php
$file = fopen( "filename.txt", 'r' );
$fsize = filesize( "filename.txt"); // reading file size
$filedata = fread( $file, $fsize );
?>

				

PHP file fwrite() function

The fwrite() function is used to write the data to a file after it is opened. It takes two arguments: the first is the file handle, and the second is the number of characters to write.

			

<?php
$file = fopen("filename.txt", 'w');
$txt = "Hello world\n";
fwrite($file, $ txt);
?>

				

PHP file close() function

Once you have completed all your read and write work on the file, you can close the file handle using the fclose() function.