Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

File Handling is essential when we are working with applications that use traditional at le

database, but there is hardly any incentive in using them over RDBMS. But there are occasions
where we need to manipulate les and this article will give you a complete overview of File
Handling in PHP.
Creating/Opening a File
We use the fopen() function to open les in PHP. If we try to open a le which doesn't exist,
then it is implicitly created. When we open a le, we specify the le mode which indicates how
we intend to use the le.
Choosing File Modes
File mode is essential because the operating system needs to know + What operations we want
to do on the le? + Whether other processes can be allowed to access the le when we are
operating on it? + Whether we have the permission for the specied operation?
File Mode is a string and the following table summarizes the available le modes and their
description
mode description
r Open le for reading only, place le pointer at the beginning of the le
r+ Open le for reading and wriitng, place le pointer at the beginning of the le
w
Open for writing only; place the le pointer at the beginning of the le and truncate
the le to zero length. If the le does not exist, attempt to create it
w+
Open for reading and writing; place the le pointer at the beginning of the le and
truncate the le to zero length. If the le does not exist, attempt to create it
a
Open for writing only; place the le pointer at the end of the le. If the le does not
exist, attempt to create it
a+
Open for reading and writing; place the le pointer at the end of the le. If the le
does not exist, attempt to create it
x
Create and open for writing only; place the le pointer at the beginning of the le.
If the le already exists, the fopen() call will fail by returning FALSE and
generating an error of level E_WARNING. If the le does not exist, attempt to
create it
x+ Create and open for reading and writing; otherwise it has the same behavior as x
c
Open the le for writing only. If the le does not exist, it is created. If it exists, it is
neither truncated (as opposed to 'w'), nor the call to this function fails (as is the
case with 'x'). The le pointer is positioned on the beginning of the le
c+ Open the le for reading and writing; otherwise it has the same behavior as c
b
This should be used in conjunction with other le modes above. This must be
used if your operating system's le system di!erentiates between binary and text
les. Windows di!erentiates but UNIX based systems don't. For portability, it is
strongly recommended that you always use the b ag.
$file = "path/to/your/file";
$fp = fopen($file, "w");
if(!fp) die("Failed opening file!");
rst parameter( filename ) is the path to the le
second parameter( mode ) is the le mode discussed above
third parameter( use_include_path - optional), which if set to TRUE , PHP searches for
the lename in include_path
Note: If $file doesn't exist, then the le will be created, so the same code above can be used
to create a le
Reading a File
The steps to be taken while reading a le are + Open the le. If the opening operation fails,
handle the error and exit + Read data from the le + Close the le
PHP provides many di!erent functions for reading les which depends on what manner we want
to read the contents of the le
Read Line by Line
We use the fgets() functions to read the contents of a le line by line. When we read line by
line, we need to stop reading once we reach the end of the le which can be determined using
the feof() function. feof takes le handle as its single parameter and returns true if the
pointer is at the end of the le.
$file = "path/to/your/file";
$fp = fopen($file, "w");
if(!fp) die("Failed opening file!");
// Read line by line
while(!feof($fp)) {
$data = fgets($fp);
echo $data;
}
fclose($fp);
Read Character by Character
We can use the fgetc() function to read a single character at a time from a le. It takes a le
handle as a parameter and returns the next character in the le.
$file = "path/to/your/file";
$fp = fopen($file, "w");
if(!fp) die("Failed opening file!");
// Read line by line
while(!feof($fp)) {
$data = fgetc($fp);
if(!feof($fp)) {
echo $data;
}
}
fclose($fp);
Note: Unlike fgets , fgetc also returns the EOF character, hence we need to test using
feof() one more time after we read the character.
Read an Arbitrary length
We can use the fread() function to read specied number of bytes from a le. It takes the le
handle as the rst argument and the number of bytes to be read as the second argument. If the
size of the le is lesser than the number of bytes specied, then it reads upto the end of the
le(EOF).
$file = "path/to/your/file";
$fp = fopen($file, "w");
if(!fp) die("Failed opening file!");
// Read 10 bytes
$data = fread($fp, 10);
echo $data;
fclose($fp);
We can use filesize() to read the entire content of a le using fread as shown below, but if
we need the entire content of a le as a string, we should use file_get_contents() since it
has better performance
$file = "path/to/your/file";
$fp = fopen($file, "w");
if(!fp) die("Failed opening file!");
// Read the whole file
$data = fread($fp, filesize($file));
echo $data;
fclose($fp);
Read the Whole File
To get the entire contents of a le as a string we can use the file_get_contents() function.
When we use this function, it opens the le whose lename is passed as the rst argument,
returns its contents as a string and nally closes the le. It is the preferred way to read the
contents of the le as a string, since its performance is very good.
$file = "path/to/your/file";
// Read the whole file
$data = file_get_contents($file);
echo $data;
Writing to a File
The steps to be taken while writing to a le are + Open the le. If the opening operation fails,
handle the error and exit + Write the data to the le + Close the le
We can use fwrite() function to write the contents of a string(second parameter) to a le
pointed to by the handle which is passed as the rst argument. It has a third parameter which is
the length. Writing the le is stopped when the length(bytes) have been written or end of the
string is reached
$file = "path/to/your/file";
$fp = fopen($file, "w");
if(!fp) die("Failed opening file!");
$data = fwrite($fp, $data); // $data contains the string to be written
fclose($fp);
Using file_put_contents() is equivalent to using fopen() , fwrite() and fclose()
successively to write data to a le.
$file = "path/to/your/file";
file_put_contents($file, $data);
It returns the number of bytes written or FALSE on failure.
Closing a File
In all the above code examples we used fclose() which is the function to close the le. It
takes the le handle as the argument and returns TRUE on succesfully closing the le.
Navigating Inside a File
We can query and the change the position of the le pointer usign the following functions
rewind() - It resets the le pointer passed as an argument to the beginning of the le.
ftell() - It returns how far in the le, the pointer position is in bytes.
$file = "path/to/your/file";
$fp = fopen($file, "w");
if(!fp) die("Failed opening file!");
$data = fread($fp, 12);
echo ftell($fp); // 11
fclose($fp);
fseek() - Sets the le position indicator for the le referenced by le handle(rst
parameter). The new position, measured in bytes from the beginning of the le, is
obtained by adding o!set(second parameter) to the position specied by whence(third
parameter).
$file = "path/to/your/file";
$fp = fopen($file, "w");
if(!fp) die("Failed opening file!");
$data = fread($fp, 12);
fseek($fp, 0); // move back to the beginning of file, same as
rewind($fp)
fclose($fp);
Deleting a File
A le can be deleted using the unlink() function. It returns TRUE on success and FALSE on
failure.
$file = "path/to/your/file";
unlink($file); // Delete the file whose path is contained in $file

You might also like