PHP File Handling

When we develop a web application using PHP, quite often we need to work with external files, like reading data from a file or maybe writing user data into file, etc. PHP File Handling So it’s important to know how files are handled while working on any web application.

File Handling Operations

File handling starts with creating a file, reading its content, writing into a file to appending data into an existing file, and finally closing the file. Php provides pre-defined functions for all these operations, so let’s start by knowing these functions.

  1. Create a File: fopen()
  2. Open a File: fopen()
  3. Read a File: fread()
  4. Write to a File: fwrite()
  5. Append to a File: fwrite()
  6. Close a File: fclose()
  7. Delete a File: unlink()

File Opening Modes

Before we look at how to open a file in PHP you need to know that a file can be opened in different modes. For example, you can open a file in read-only mode or in read and write modes. Take a look at the table below for the different modes:

Modes Description

r         Read only. Starts at the beginning of the file
r+       Read/Write. Starts at the beginning of the file
w       Write only. Opens and clears the contents of the file; or creates a new file if it doesn’t exist
w+     Read/Write. Opens and clears the contents of the file; or creates a new file if it doesn’t exist
a        Append. Opens and writes to the end of the file or creates a new file if it doesn’t exist
a+      Read/Append. Preserves file content by writing to the end of the file
x         Write only. Creates a new file. Returns FALSE and an error if the file already exists
x+       Read/Write. Creates a new file. Returns FALSE and an error if the file already exists

 

Creating a File

When we use the function fopen() to open a file that doesn’t exist then that file gets created. PHP File Handling

Let’s take an example,

$myfile = 'log.txt';
//opens the log.txt file or implicitly creates the file
$file = fopen($myfile, 'w') or die('Cannot open file: '.$myfile);

fopen() function takes the filename as the first argument and the second argument represents the mode in which the file will be opened.

The log.txt file will contain the following lines:

welcome to PHP File Handling tutorial.
you will learn about how to create, open, read, write, and append file.

Opening a File

To open a file in PHP you can use the fopen() function. This function takes two parameters, where the first parameter contains the name of the file and the second parameter is the modes that should be used to open the file.

Take a look at an example:

<?
$file=fopen("log.txt","w");
? >

In this example, we are trying to open file log.txt in write mode. If the fopen() function is unable to open the specified file, it returns 0 (or false).

Closing a File

After you have opened a file and you are done (for instance reading its contents) then you should close the file. A fopen() function should always match with a fclose() function. PHP File Handling

Take a look at an example:

<?
$file = fopen("log.txt","r");
//do something with the file log.txt
fclose($file);
?>

Reading a File

We can read content from an already open file using the fread() function. The fread() function takes two arguments:

  1. first is the filename
  2. and the second argument specifies the size in bytes for the content to be read.

If we want to read entire content of the file, we will open the file in read mode and then use the fread() function.

<?php
// Opening a file
$file = fopen("log.txt", "r");
 
// reading the entire file using fread() function
echo fread($file, filesize("log.txt"));
       
// closing the file
fclose($file);
?>

The output will be the content present in the log.txt file.

Reading a File Line by Line

The fgets() function is used to read a single line from a file. After the line has been read the file pointer is pointing to the next line in the file. This is very useful, because we could now read the file line by line.

Before we show you the example we have to talk about the feof() function. This function can be used to check if the “End-Of-File” (EOF) has been reached. This is very useful because we now can loop through a file of unknown length. We can do this on every file that is not opened in w, a, and x mode!

Let’s take a look at an example:

<?
$file = fopen("log.txt", "r") or exit("Unable to open the file!");
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>

First, we open the file test.txt in read mode. If this is not possible, we exit with a message. Then we use a while loop to loop through the file. This is done until we reach the end of the file. In the loop, the fgets() function is used to grab one line and echo this line onto the screen. The last thing that is done is closing the file.

Write to a File with PHP

fwrite() function is used to write content to a file when a file is already open in write mode.

Let’s take an example, where we will write a couple of movie names to our file movies.txt

$file_name = 'movies.txt';
//opens the file.txt file or implicitly creates the file
$file = fopen($file_name, 'w') or die('Cannot open file: '.$file_name);
$movie_name = "The Deep Blue See n";
// write name to the file
fwrite($file, $movie_name);

// let's write another movie name to our file
$movie_name = "Ghost Rider n";
fwrite($file, $movie_name);
// close the file
fclose($file);

In the code above we wrote two movie names in the file movies.txt. f we open the file, it will look like the following:

Output:
The Deep Blue See
Ghost Rider

Note: When a file is opened in write mode, all the existing data in the file is erased and new data can be written to the file using the fwrite() function.

If we again open the above file to write more content to it, and we open the file in write mode then all the existing content will be erased.

Append data to a File with PHP

If we wish to add more movie names to the file movies.txt then we need to open the file in append mode. Let’s take an example and see.

$file_name = 'movies.txt';
//opens the file.txt file or implicitly creates the file
$file = fopen($file_name, 'a') or die('Cannot open file: '.$file_name);
$movie_name = "Avengers n";
// write name to the file
fwrite($file, $movie_name);

// lets write another movie name to our file
$movie_name = "Real Steel n";
fwrite($file, $movie_name);
// close the file
fclose($file);
Output:
The Deep Blue See
Ghost Rider
Avengers
Real Steel

 

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.