PHP Tutorials: File Handling

Every programming language either server-side or client-side has the capability to work with files and directory on the system or on the server. Since PHP is a server side language so it has capability to handle files and directories on server and manipulate them using the file handling system.

File handling system is a set of functions, that are used to open a file, to read a file, to delete a file, and to modify a file. The same things can be done with the directors as well.

To work with any file we have to open the file and create a resource before we do any operation with the file. In this tutorial we will see that how we can open a file with various modes. Mode defines the current state of file which we can use further.

Open a file with fopen()

As mentioned earlier to work with any file we have to open it first. The fopen() function helps us to open a file. The fopen() function takes two parameter, the first parameter is the name of the file and another is the mode of opening the file.

Syntax:
fopen(filename, mode);

I’m sure you are eager to know the various modes which we can use to open a file in the file system. Following is the list of the modes which we can use.

ModeFeature
rOpen the file for reading only.
r+Open the file for reading and writing.
wOpen the file for writing only and clears the contents of file. If the file does not exist, PHP will attempt to create it.
w+Open the file for reading and writing and clears the contents of file. If the file does not exist, PHP will attempt to create it.
aAppend. Opens the file for writing only. Preserves file content by writing to the end of the file. If the file does not exist, PHP will attempt to create it.
a+Read/Append. Opens the file for reading and writing. Preserves file content by writing to the end of the file. If the file does not exist, PHP will attempt to create it.
xOpen the file for writing only. Return FALSE and generates an error if the file already exists. If the file does not exist, PHP will attempt to create it.
x+Open the file for reading and writing; otherwise it has the same behavior as ‘x’.

Since we have seen the function syntax and the mode. Let us take an example and see how it works.

<?php
$filename = "info.txt";
$handle = fopen($filename, "r");
?>

In the above example we used the fopen() function with r mode that means we are opening the file just to read. While working with file handling we also have to make sure that the file we are opening does exist, otherwise the program will give a warning message. In the above example we haven’t handle the error if file does not exist. To ignore the warning message we have to use a function called file_exists(). The function will tell us wether the file exists or not. Let us take an example with the function file_exists().

<?php
$filename = "info.txt";
 
// Error handling: Check if file exists or not
if(file_exists($filename)) {
    // Open the file for reading
    $handle = fopen($filename, "r") or die("Cannot open the file.");
        
    // Read fixed number of bytes from the file
    $content = fread($handle, "100");
        
    // Close the file handle
    fclose($handle);
        
    // Display the file content 
    echo $content;
} else {
    echo "Make sure the file you are opening does exists.";
}
?>

Write into a file with fwrite()

In the above example we have seen that how we can open a file using fopen() function in a read mode. Now we will see how we can write into a file using a fwrite() function. The fwrite() function takes two parameters. The first is the file handle and another is a content to write. While opening a file to write we must open the file in write mode.

Let us take an example and see how fwrite() works.

<?php
$filename = "info.txt";
    
// Content to write into the file
$content = "Hello World! This is an example of writing into file using fwrite().";
    
// Open the file in write mode
$handle = fopen($filename, "w") or die("Cannot open the file.");
    
// Write data
fwrite($handle, $data) or die ("Error while writing into file.");
    
// Closing the file handle
fclose($handle);
    
echo "Operation successful.";
?>

The above example we have seen that how we can write content into a file. With the w mode if the file does not exist the system will create a file in the current directory. With a w mode it overrides the file and writes the fresh content into it. However if you wanted to modify the file or say append the content into the file you can open the file in a mode

Close a file with fclose()

It is very important to close the file after you use and finish the operation. Otherwise it will keep the resource busy and keep filling the program memory. What is the program memory get exhausted the program will slow down the performance and may also show error of memory exhaust. It is always the best approach to close the file just after you finish the operation. The apps close function is used to close the file. The floor function except single parameter and that is the file handle we created while opening the file.

Take an example to see how we can close the file after doing the operations.

<?php
$file = "data.txt";
 
// Check the existence of file
if(file_exists($file)){
    // Open the file for reading
    $handle = fopen($file, "r") or die("ERROR: Cannot open the file.");
        
    /* Some code to be executed */
        
    // Closing the file handle
    fclose($handle);
} else{
    echo "ERROR: File does not exist.";
}
?>

Leave a Reply

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