File Handling in PHP - Page 1
       by Jeff Wheeler aka nokrev | 5 July 2006

When writing applications for the web, it's often important to be able to save data. This is usually done one of two ways: writing data to a file, or saving it in a database (such as MySQL). Of course, the easier method (which doesn't require other technologies) is to write to files, and then read and parse them yourself. This simpler which is what I discuss here.

So, let's get started:

  1. To open a file for reading and writing, we start by using the fopen function. This simply opens up a file resource for us to use in later functions.



    It's worth noting that I opened the file for reading. Notice the 'r'? This is the mode argument, and allows you to use the $file variable for reading, or writing, depending on which you need.

    You can see the different modes for opening a file in the documentation for the function (under Table 1).
  2. To read from a file, the easiest way is to utilize the fread method. This takes two arguments, the file resource from the previous function (fopen), and a length argument.



    I had to use filesize in order to read to the end of the file. Otherwise, the function won't know when to stop reading.
  3. Writing to a file is done with similar ease. This time, we'll just use fwrite, which has two required arguments: the file handle resource, and the string to write (the third optional argument is the length of the content to write).



    I had to redefine the $handle variable, because the previous resource was only open for reading.

The Shortcuts
Well, since you know how to open, read, and write files the full, long way, here are some shortcuts. I tend to avoid these, but there's really nothing wrong with using them. Please be aware, both of these require PHP5.

  1. Rather than fopen and fread, you can simply use file_get_contents. The only required argument is the filename, and it'll return a string of the contents.

  2. Now, the shortcut for fwrite is just as simple…

 

On the next page, I will cover how to list files in directories and more!

Onwards to the next page!

1 | 2 | 3




SUPPORTERS:

kirupa.com's fast and reliable hosting provided by Media Temple.