File Handling
File Handling
File Handling
how to read a file line by line and how to read a file character by character.
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
w Write only. Opens and clears the contents of file; or creates a new file if it doesn’t exist
w+ Read/Write. Opens and clears the contents of 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
x Write only. Creates a new file. Returns FALSE and an error if file already exists
x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists
Opening a File
To open a file 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.
<html>
<body>
<?php
$file=fopen("test.txt","w");
? >
</body>
</html>
In this example we are trying to open een file test.txt in write modes. If the fopen() function is unable to open the specified
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. Take a look at an example:
<?php
$file = fopen("test.txt","r");
fclose($file);
?>
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
<?php
$file = fopen("test.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. Than 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.
<?php
$file = fopen("test.txt", "r") or exit("Unable to open the file!");
while(!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>
As you can see it is almost the same as the previous example. The only thing that’s changed is the function fgets() in fgetc()
Opening a file
Reading a file
Writing a file
Closing a file
Files modes can be specified as one of the six options in this table.
Mode Purpose
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.
The following example assigns the content of a text file to a variable then
displays those contents on the web page.
<html>
<head>
<title>Reading a file using PHP</title>
</head>
<body>
<?php
$filename = "tmp.txt";
$file = fopen( $filename, "r" );
</body>
</html>
The following example creates a new text file then writes a short text
heading inside it. After closing this file its existence is confirmed
using file_exist()function which takes file name as an argument
<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
<head>
<title>Writing a file using PHP</title>
</head>
<body>
<?php
$filename = "newfile.txt";
$file = fopen( $filename, "r" );
fclose( $file );
</body>
</html>
Syntax :
resource fopen ( string $filename , string $mode [, bool $use_include_path =
false [, resource $context ]] )
Example
<?php
?>
Syntax :
Example
<?php
fclose($handle);
?>
file size.
Syntax :
$filename = "c:\\myfile.txt";
fclose($handle);//close file
?>
Syntax :
Example
<?php
fclose($fp);
?>
output : File written successfully
Syntax :
Example
<?php
unlink('data.txt');
?>
Using PHP file handling mechanism, we can get external file resources to store
as a reference. We have slightly touched about file resources while
discussing PHP Resource Data.
PHP provides set of in-built functions to handle files. Some of the functions
are, fopen(), file_exists(), file_get_contents() and etc.
Some of the basic operations to deal with files are listed below.
Opening file
Working with file read, write and append
Closing file
Opening file
To open a file, we need to specify the name of that file and mode. The mode
of operation deals with the access limitation of the file to be opened.
Mode of Operation
In PHP file handling, there are four set of possible modes. These are,
In PHP, the following types of two file handling modes are used to read
existing file. The file pointer will point to the start of the file.
Using fopen() function, we can open a file by it’s name and corresponding
mode. For example,
$filePointer = fopen("hello.txt","r");
while(!feof($filePointer)){
echo fgets($filePointer). "<br>";
}
Note: We should ensure that the specified file exists. If not, the following error
will occur,
Warning: fopen(hello.txt) [function.fopen]: failed to open stream: No such
file or directory in ...
To perform the write operation, we have two choices to select the mode of the
file to be opened. These are,
By using these modes, the entire file content will be cleared and the pointer
will focus the start position of the file content. This method is used to change
the existing file content, completely.
For example,
$filePointer = fopen("hello.txt","w");
fwrite( $filePointer, "PHP POT: MySQL Query\n" );
In this operation, the existing content of the file will not be cleared. Rather, we
can add new content continuously. Here, file pointer will point end of the file.
And the possible mode of operations are,
Mode of Operation File Mode File Pointer Position
The code will be similar to that of file-write except the mode specified to open
the file. For example,
$filePointer = fopen("hello.txt","a");
Note: In PHP, write and append mode will open the specified file if exists.
Otherwise, a new file will be created for performing file write and append.
Here also two file handling modes available that are used to write into a newly
created file.
x write-only. –
x+ read-write. –
For example,
$filePointer = fopen("hello.txt","x");
fwrite( $filePointer, "PHP POT: FUNCTIONS\n" );
Caution: is already exists, then the execution will be stopped with the
following error.
Warning: fopen(hello.txt) [function.fopen]: failed to open stream: File exists
in ... on line ...
Warning: fwrite() expects parameter 1 to be resource, boolean given in ... on
line ...
Closing File
After performing all the above file operations of PHP, we need to close it by
using the fclose() function. fclose() function should hold the file pointer which
is the reference for the file resources. In PHP, we can use fclose() as shown
below.
fclose( $filePointer);
File handling is an important part of any web application. You often need to open and process a
file for different tasks.
You can do a lot of damage if you do something wrong. Common errors are: editing the wrong file,
filling a hard-drive with garbage data, and deleting the content of a file by accident.
Assume we have a text file called "webdictionary.txt", stored on the server, that looks like this:
Example
<?php
echo readfile("webdictionary.txt");
?>
The readfile() function is useful if all you want to do is open up a file and read its contents.
The first parameter of fopen() contains the name of the file to be opened and the second parameter
specifies in which mode the file should be opened. The following example also generates a message if
the fopen() function is unable to open the specified file:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
Run example »
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File
pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file.
Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File
pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the
file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
The first parameter of fread() contains the name of the file to read from and the second parameter
specifies the maximum number of bytes to read.
The following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));
PHP Close File - fclose()
The fclose() function is used to close an open file.
It's a good programming practice to close all files after you have finished with them. You don't want
an open file running around on your server taking up resources!
The fclose() requires the name of the file (or a variable that holds the filename) we want to close:
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
The example below outputs the first line of the "webdictionary.txt" file:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
Run example »
Note: After a call to the fgets() function, the file pointer has moved to the next line.
The feof() function is useful for looping through data of unknown length.
The example below reads the "webdictionary.txt" file line by line, until end-of-file is reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
Run example »
The example below reads the "webdictionary.txt" file character by character, until end-of-file is
reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
Note: After a call to the fgetc() function, the file pointer moves to the next character.
If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing
(w) or appending (a).
The example below creates a new file called "testfile.txt". The file will be created in the same directory
where the PHP code resides:
Example
$myfile = fopen("testfile.txt", "w")
PHP File Permissions
If you are having errors when trying to get this code to run, check that you have granted your PHP file
access to write information to the hard drive.
The first parameter of fwrite() contains the name of the file to write to and the second parameter is
the string to be written.
The example below writes a couple of names into a new file called "newfile.txt":
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the file we sent the string
$txt that first contained "John Doe" and second contained "Jane Doe". After we finished writing, we
closed the file using the fclose() function.
John Doe
Jane Doe
PHP Overwriting
Now that "newfile.txt" contains some data we can show what happens when we open an existing file
for writing. All the existing data will be ERASED and we start with an empty file.
In the example below we open our existing file "newfile.txt", and write some new data into it:
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
If we now open the "newfile.txt" file, both John and Jane have vanished, and only the data we just
wrote is present:
Mickey Mouse
Minnie Mouse
Opening a File
The PHP fopen() function is used to open a file.It requires two arguments stating first the file name and then mode in which to
operate.
The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode
the file should be opened:
<html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>
Files modes can be specified as one of the six options in this table.
Mod
Description
e
Read only. Opens the file for reading only.
r
Places the file pointer at the beginning of the file.
Read/Write.Opens the file for reading and writing.
r+
Places the file pointer at the beginning of the file.
w Write only.Opens 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
Mod
Description
e
exist then it attemts to create a file.
Read/Write.Opens the file for reading and writing only.
Places the file pointer at the beginning of the file.
w+
and truncates the file to zero length. If files does not
exist then it attemts to create a file.
Append.Opens the file for writing only.
a Places the file pointer at the end of the file.
If files does not exist then it attemts to create a file.
Read/Append.Opens the file for reading and writing only.
a+ Places the file pointer at the end of the file.
If files does not exist then it attemts to create a file.
Write only.Creates a new file. Returns FALSE and an error if file
x
already exists
Read/Write.Creates a new file. Returns FALSE and an error if file
x+
already exists
If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file pointer which is used for further
reading or writing to that file.
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.
Note: If the fopen() function is unable to open the specified file, it returns 0 (false).
Example
The following example generates a message if the fopen() function is unable to open the specified file:
<html>
<body>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
</body>
</html>
Closing a File
The fclose() function is used to close an open file:
<?php
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
?>
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's 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 here are the 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.
The following example assigns the content of a text file to a variable then displays those contents on the web page.
<html>
<head>
</head>
<body>
<?php
$filename = "/home/user/guest/tmp.txt";
exit();
fclose( $file );
echo ( "File size : $filesize bytes" );
echo ( "<pre>$filetext</pre>" );
?>
</body>
</html>
Reading a File Line by Line
The fgets() function is used to read a single line from a file.
Note: After a call to this function the file pointer has moved to the next line.
Example
The example below reads a file line by line, until the end of file is reached:
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br>";
}
fclose($file);
?>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>
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.
The following example creates a new text file then writes a short text heading insite it. After closing this file its existence is confirmed
using file_exist() function which takes file name as an argument
<?php
$filename = "/home/user/guest/newfile.txt";
exit();
fclose( $file );
?>
<html>
<head>
</head>
<body>
<?php
{
$filesize = filesize( $filename );
echo ($msg );
else
?>
</body>
</html>