Reading and Writing Files

4.63 (76)

Introduction

I'm sure many of you use databases, such as the ever popular MySQL, to hold all your website content, articles, possibly even images. What many of you may not know is that before databases, everyone used to use flat files. Actually, databases are simply flat files with some special data arrangements and indexing. So what are flat files? Simply put, they are ordinary files that you and I manipulate every day, such as txt files, images and word documents.

Databases really are wonderful pieces of software, they allow us to organize our content logically and allow easy access, updating and searching. However, sometimes a database is overkill and is not needed for the task. For example, what if you had a list of sayings or quotes, and you would like to display a random one each time the page loads. This could easily be represented in a database; however, it is equally as easy to do it using flat files.

Getting Started


Let's jump right into reading and writing files then. Firstly, we are going to define our file with some common sayings in it, so that we can start off by reading them. I am going to call the file randomsayings.txt and it will be saved in the same directory as the PHP script is saved in.

randomsayings.txt
Patience is a virtue.
Three's a crowd.
43% of all statistics are wrong.
There are 10 types of people; those who understand binary and those who don't.
After all is said and done, more is said than done.
The biggest man you ever did see was once a baby.
It's only a game!


Go ahead and create a file and save it in some directory before we continue.
There are some important things to know about reading and writing files using PHP. Most importantly, file modes and how to actually open a file for reading and writing.

A file mode, is the way in which you are going to use the file. Hence, reading a file is one mode, writing is another mode and appending is another mode. These are represented by the characters r, w and a respectively. There is additional modes such as the 'exclusive' mode represented by x. This is a special mode in which it assumes the file does not exist and will attempt to create it. If the file already exists there will be an error.

Conversely, the write and append mode (w and a) will also create the file, but only if it does not exist. This is quite useful compared with the exclusive mode, which is infrequently used.

There are special modifiers to these modes, the +, b and t modifiers. The first modifies the previous mode so that both reading and writing are always allowed. E.g. w+ would indicate file writing but also allowed to read the file. The second modifier (b) stands for binary mode and is very useful. Some operating systems, mainly Microsoft Windows distinguish between text and binary files (data files) as different types which can be confusing. By using the binary mode, all action will be completed as if you are reading data, or basically, reading the file for how it is. It is generally recommended to always use this mode when using file handling. I will not talk about the last mode as it is strongly recommended that it should not to be used.

Opening Files


When I say 'opening files', I am referring to creating a resource, so that we can manipulate data in this associated file. This means, that when we want to write to a file we must mention which resource we are acting upon.

Using the fopen() function we can create these resources, as well as define what mode we are going to use. The fopen() function is defined as:

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


Importantly, it is shown that fopen() returns a variable of type resource. This function has two compulsory parameters being filename and mode. The other two parameters are not necessary and rarely used.

The filename is as it says, the name of the file we are going to open. This can be a path also, so if you want to open a file in a different directory you could use something similar to ../text/randomsayings.txt as your file name. The mode is what was discussed before; the method of using the file.

Let's take a simple example:

First Example
<?php
if (!$file fopen('randomsayings.txt''a+b')) {
    echo 
'Error whilst opening the file.';
} else {
    echo 
'File Opened Successfully';

    
fclose($file);
}

?>


This simple example demonstrates two important features; the usage of fopen() and how to use the resource variable. As you can see, we have used the function as described and supplied a file name and mode. The mode we have used, allows for both appending and reading of the file, and is also using binary mode so that no incompatibilities occur.

The fopen() function returns the resource, which we define to be $file. We test if the function worked correctly, and then we close the file. It is very important to always close your file, otherwise it can possibly be left open, which can keep it locked, or use up system resources. To close our file, we simply pass our file resource $file to the fclose() function.

Now that you're up to par on the basics, move on and we'll start reading some files.
Rate this article: BAD 1 2 3 4 5   GOOD
Page 1 of 3    >>

Build Your Own Database Driven Website Using PHP & MySQL

  • Installation instructions for Windows, Linux and Mac OS X
  • Instantly apply working code examples from the book to your Website
  • Build a working Content Management System from scratch
  • Master MySQL database administration
  • Fully updated for PHP 5

       Download FREESample Chapters Now!

Ads

PHPNerds Newsletter