Home arrow PHP arrow Page 2 - Working With Text Files in PHP

Working With Text Files in PHP

Sure, you know PHP's MySQL functions, but do you know how to read/write files in PHP? If not, then make sure you read this article. In it, Mitch teaches you everything you need to know to successfully work with files in PHP...

Author Info:
By: Mitchell Harper
Rating: 5 stars5 stars5 stars5 stars5 stars / 103
December 18, 2002
  1. · Working With Text Files in PHP
  2. · Opening and Reading Files
  3. · Creating and Writing Files
  4. · File Writing in Action
  5. · Conclusion

print this article

Working With Text Files in PHP - Opening and Reading Files
(Page 2 of 5 )

More often that not, you will be opening and reading files as opposed to writing them. There are 3 main functions that we can use to open and read files in PHP:

fopen stands for "file open", and is used to create a pointer to the file which we want to open for read/write access. It accepts 2 required and 2 optional parameters. Its signature is shown below:

int fopen ( string filename, string mode [, int use_include_path [, resource zcontext]])

For example, let's say that we wanted to open a file called test.txt. We would use fopen like this:


$fp = fopen("test.txt", "r");


The $fp variable would now contain a pointer (or reference) to the test.txt file. The second parameter, "r", tells PHP that we want to open the file in read mode only –- we don't actually want to write to the file. One-way file operations are quicker than 2 way operations (such as read+write access) because the location of the file pointer is uni-directional, i.e. it only has to travel down the file, and not jump from position to position.

There are 6 different file modes that we can use when working with files in PHP. They are shown below (courtesy of php.net):
  • 'r' - Open for reading only; place the file pointer at the beginning of the file.
  • 'r+' - Open for reading and writing; place the file pointer at the beginning of the file.
  • 'w' - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
  • 'w+' - Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
  • 'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
  • 'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
As you can see, PHP is very flexible when it comes to files. We can read a file, read and write to a file, append to the end of a file, move the file pointer to the bottom of the file automatically and more!

Now that we're familiar with the fopen function, let's look at the feof and fread functions.

Yes, it sounds like some sort of greek god name, but it's actually the function that we can use in PHP to determine whether or not we have reached the end of a file when we're reading it in. All file functions are prefixed with the character "f" in PHP, and EOF is an acronym for End-Of-File.

Feof is a simple function, and accepts just 1 parameter, as shown below:

int feof ( int fp)

The parameter, fp, is a reference to a file pointer that contains the details of the file we're working with. Feof returns true if we're at the end of a file, and false if we're not.

Before we can see the feof function in action, we need to learn a bit about the fread function, which we will look at next.

I really do love the flexibility of PHP. You can do things the long way (if you've come from a C++ background for example), or you can do things the short way. For example, in PHP there are 2 different functions that you can use to read in a file. They are called fgets and fread. Take a look at some code for each in the examples below, and tell me which one you’d rather use:

// fgets example


$fp = fopen("test.txt", "r");
$data = "";

$data .= fgets($fp, 4096);

echo $data;


// fread example


$fp = fopen("test.txt", "r");
$data = fread($fp, filesize($fp));

echo $data;


Fairly easy choice, right? Fgets grabs a line from the file, whereas fread grabs a certain amount of characters from the file. Let's examine our fread example in further detail:

$fp = fopen("test.txt", "r");

We start by using the fopen function to open the "test.txt" file for reading only. The file pointer to test.txt is stored in the variable called $fp.

$data = fread($fp, filesize($fp));

Next, we grab the entire contents of our test.txt file by passing 2 parameters to the fread function:
  • $fp is the file pointer to our test.txt file
  • filesize($fp) is a PHP function which accepts a pointer to a file. It returns the length of that file in bytes
After this line has executed, $data will contain the entire contents of our test.txt file -- whether it be text or binary. The signature of the fread function looks like this:

string fread ( int fp, int length)

As we've already discussed, we pass in a file pointer ($fp in our example) and also the number of bytes that we want to retrieve from the file. The filesize() function returns the length of our file by simply passing it the file pointer.

If you're reading in binary data on a Windows PC, then you need to use "rb" as the file mode instead of just "r".

Putting it All Together
OK, so now you know about the 4 functions that we need to open and then read-in the contents of a file: fopen(), foef(), fread() and filesize(). Let's create a PHP script that will read some values in from a text file.

Create a text file called "person.data" and add the following lines to it:


Create a file called getperson.php and add the following code to it (make sure you save it in the same directory as person.data:


$fp = @fopen("person.data", "rb") or die("Couldn't open file");
$data = fread($fp, filesize($fp));

$data .= fgets($fp, 1024);


$values = explode("\r\n", $data);

echo "Name: " . $values[0] . " " . $values[1] . "<br>";
echo "Age: " . $values[2] . "<br>";
echo "Sex: " . $values[3];


The output from getperson.php looks like this:

The output from getperson.php

In the example above, I decided to use fgets() instead of fread(). Notice also that I've called fclose() after I have read-in the contents of the file. Fclose() simply releases the pointer to the file and frees up the memory that all file operations associated with that pointer were using.

[Note] Instead of using explode to split the contents of the file into an array, I could have just used

echo $data;

... to output the contents of the entire file. [End Note]

OK, are you familiar with how to open and read the contents of a file now? Good! Because now we're going to learn how to create and write to files...
blog comments powered by Disqus

- Removing Singletons in PHP
- Singletons in PHP
- Implement Facebook Javascript SDK with PHP
- Making Usage Statistics in PHP
- Installing PHP under Windows: Further Config...
- File Version Management in PHP
- Statistical View of Data in a Clustered Bar ...
- Creating a Multi-File Upload Script in PHP
- Executing Microsoft SQL Server Stored Proced...
- Code 10x More Efficiently Using Data Access ...
- A Few Tips for Speeding Up PHP Code
- The Modular Web Page
- Quick E-Commerce with PHP and PayPal
- Regression Testing With JMeter
- Building an Iterator with PHP

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2019 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials