Chapter 7 - Reading and Writing to Files

By: Albert Ritzhaupt

 

 


Chapter Topics

Basic File Processing  

Files are the basic unit of storage for information on a hard drive.  PHP has the capability to manipulate files by reading, writing, and appending.  You can read from a file and manipulate the information to create dynamic websites, you can write to a file to capture information from HTML forms, or both.   You will find that reading and writing from and to files requires many of the skills you learned in the previous chapters, which includes arrays, functions, and control structures.

As mentioned, a file can serve as input to a program (reading) or output from a program (writing).  Sometimes we will read and write to the same file.  The figure below visualizes a file in relation to a PHP program.  The unidirectional arrows represent reading or writing, and the bidirectional arrows represent both.

File Diagram

Depending on what you are trying to accomplish with you program, you may use any of the above methods.  In the following sections we will investiage the syntax for file processing and some of the requirements.  The basic steps to file processing, regardless of the purpose, will generally include the following:

  1. Open the specified file
  2. Check to determine if there was an error with the opening
  3. Process the file by reading, writing, or appending
  4. Close the file

    back to top

Opening a File

Before you can read or write from or to a file, you must open the file.  To open a file, you first make a decision about two things: (1) determine the location of the file, and (2) determine the operation you intend to perform on the file.  The fopen() function is used to open files and includes two parameters: the file's location, and the operation.  There are three primary operations: (r) read, (w) write, and (a) append.  PHP requires you to state your intentions, meaning that you must define what you intend to do with the file.

The source code below provides a simple example of each of the cases.  Notice that the default location is the present working directory.  Therefore if you simply provide a file name as the parameter, it will point to the directory the PHP program resides in.

//Example 1 - Open to read from file
$file_name = "file.txt";
$fp = fopen($file_name, "r");

//Example 2 - Open to write to file (overwrite) in the
//parent directory

$file_name = "../file.txt";
$fp = fopen($file_name, "w");

//Example 3 - Open to append to file (not overwrite) in the
//a child directory

$file_name = "someDirectory/file.txt";
$fp = fopen($file_name, "a");

 

Notice that you can use a relative path to point to the file you wish to operate in.  The first example includes writing to a file in the parent directory, while the second example appends to a file in a child directory named someDirectory.  You can also use absolute paths if you want.  The fopen() function returns a file handle.  This is a variable that points to the the file on the system and is used by other functions in the subsequent discussion.

It is also important to note that in the second example, if the file does not exist, it will be created by PHP.  You must check that you have granted your PHP file access to write information to the hard drive. Setting permissions is discussed in Chapter 1.

back to top

Closing a File

Every file you open should also be closed.  Closing a file in PHP is much easier than opening a file.  It is accomplished using the fclose() function.  As shown in the source code example below, you simply pass the file handle to the function as a parameter.  You should do this after you have completed whatever operations you intended to perform, such as reading or writing.

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

...

fclose($fp);
 

If you do not close your file, you will likely encounter run-time errors.  Remember to always close your files.  

back to top

Reading from a File

The first operation we are going to learn about is reading from a file.  Of course, in order for you to be able to read from a file, you must have a file available on the hard drive that has read permission access (chmod).  The figure below shows the text that is available in a file named "veg.dat".  This data is going to be read by a PHP program.

Potato 
Carrot
Lettuce
Spinach
Stack
 

The file contains a list of vegtables.  The source code below shows how the information will be read by a PHP program and presented as an ordered list.  To read from a file, we are going to use the fgets() function.  There is another function available for reading from files: fread().  It will not be discussed in this text, but may be of value.  For more information, consult the mannual.

Notice that the veg.dat file contains data that is seperated by new lines.  The fgets() function is best suited for information that is structured this way.  The fgets() function reads from the begining of the line to the end of the line.  Notice, that the file contains more than one line.  To read all the lines, we must use a repitition control structure - the while loop.

$file_name = "veg.dat"; 
$fp = fopen($file_name, "r");
echo "<ul>";
while($line = fgets($fp))
{
echo "<li>$line";
}
echo "</ul>";
fclose($fp); 

Each line in the file is requested from the fgets() function in sequential order.  Each time the loop executes, the line is printed to the screen as a bulleted item.  The while loop continues to execute until there are no more lines in the file.  For an example of the output of this program, click the link below.

>>Program Example 1

back to top

Writing to a File

As mentioned, you can also use PHP to write to a file.  There are two ways to write to a file: write and append.  If you choose to write to a file, you will effectively overwrite the information that was there prior to the write.  This may not be useful if you are trying to collect information from a group of people.  In most cases, you will want to append to a file.  In this example, we are going to collect a list of names.  The HTML source code below is for a simple form to capture a person's name and add it to a list.

<html>
<body>
<form action="example2.php" method="post">
Your Name: <input name="name"><br>
<input type="Submit" value="Add Name">
</form>
</body>
</html>

The PHP program first needs to capture the name and open the file for appending.  After the name has been captured and file is opened, we can append the information to the file.   We can use the fwrite() function to append to files.  The fwrite() function takes two parameters: the file handler and the string to be appended to the file (we use \n to adda new line after the name).  Notice the program appends the information to the file, closes the file, opens the file for read access, and displays the information to the screen.  We have to close the file from append access and reopen it for read access.

<?php
$name=$_POST['name'];
$file_name = "names.dat";
$fp = fopen($file_name, "a");

//write to the file
fwrite($fp, "$name\n");
fclose($fp);

//read from the file
$fp = fopen($file_name, "r");
echo "<ul>";
while($line = fgets($fp))
{
echo "<li>$line";
}
echo "</ul>";
fclose($fp); 
?>

If you wanted to write to a file and overwrite the contents, you would use the 'w' option as a parameter of the fopen() function.  Also, keep in mind that the names.dat file must already be available and set to the correct permissions.  In this case, you would set names.dat to chmod 706 names.dat.  For an example of the program above, click the link below.

>>Program Example 2

back to top

Putting it all Together: strtok()

In this final section, we are going to learn about the strtok() function which is extremely useful for parsing string information.  In this particular example, we have two fields that are available in a file.  We are going to read the file, and parse the fields using the strtok() function.  We will then print the fields in a different order.  The figure below shows the contents of the text file.  As you can see, the first field is a person's first name and the second field is the last name.

Ayn|Rand|Atlas Shrugged
Jules|Verne|20,000 Leagues Under the Sea
B.F.|Skinner|Walden II
Art|Spiegelman|Maus
Dale|Carnegie|How to Win Friends and Influence People

As you can see, the file contains a list of authors and one of the books they are known for publishing.  We are going to read this data and format it in a meaningul way.  The program below reads the data, and prints it with a label for first name, last name, and book title.  Remember to change the permission for both the input file and the program.

<?php
//read from the file
$file_name="authors.dat";
$fp = fopen($file_name, "r");
while($line = fgets($fp))
{
$fName = strtok($line, "|");
$lName = strtok("|");
$title = strtok("|");
echo "<b>First Name:</b> $fName<br>";
echo "<b>Last Name:</b> $lName<br>";
echo "<b>Book Title:</b> $title";
echo "<br><hr><br>";
}
fclose($fp); 
?>

The strtok() function takes two parameters.  The first parameter is the line of data that has been read into memory.  Technically, it is nothing more than a string.  The second parameter is the delimiter - that which separates each of the fields.  The function returns the data in the order it appears in the file.  The first time you must pass both parameters.  The subsequent calls should only include the delimiter.  Keep in mind that if the character used as a delimiter is found in one of the fields, it will likely cause run time errors.  Be selective when choosing the delimiter.  For an example of this program, click the link below.

>>Program Example 3

back to top

Your Seventh Program

This section will provide the steps for you to create your sixth PHP program. 

  1. First create a file named "seventh.html" in a directory that is recognized by the web server. The file should contain the following information:

    <html>
    <form action="program7.php" method="post">
    Grocery Item: <input name="item"><br>
    Amount: <input name="amount"><br>
    <input type="Submit" value="Add Item">
    </form>
    </html>

  2. Now let's create the source code for the program.  Create a file named "program6.php" in the same directory as "sixth.html".  The file should contain the following information:

    <?php
    $item=$_POST['item'];
    $amount=$_POST['amount'];
    $file_name = "grocery.dat";
    $fp = fopen($file_name, "a");

    //write to the file
    fwrite($fp, "$item|$amount\n");
    fclose($fp);

    //read from the file
    $fp = fopen($file_name, "r");
    echo "<h3>Grocery List</h3>"; 
    echo "<ul>";
    while($line = fgets($fp))
    {
    $item = strtok($line, "|");
    $amount = strtok("|");
    echo "<li>$item - $amount";
    }
    echo "</ul>";
    fclose($fp); 
    ?>

  3. You must create an empty file named 'grocery.dat' in the same directory.  After you have created the file and put the information into the files, save your work, and change the permissions of the files to:

    prompt$: chmod 704 seventh.html
    prompt$: chmod 705 program7.php

    prompt$: chmod 706 grocery.dat

  4. Open the URL to the location where you saved the file (seventh.html) and you should be able to play the number game.

Congratulations! You have completed the seventh chapter. You can now take the online assesement, complete the seventh activity, and move to the next chapter. 

>>Take the Online Quiz

back to top

Activity 7

Create a PHP file named index.php with a simple HTML form to capture the following information:

  • Full Name – The full name of the person signing your guestbook.
  • Homepage – The URL (website) of the person signing your guestbook.

The form should action should point to the index.php (same file) file using the POST
method. After you have created the form, you need to create the source code to show
the contents of the guestbook, which is a file that should be in the same directory
named guest_list.txt. This file will contain all the entries to your guestbook. The guest_list.txt file should have the following file structure:

Full Name | Date Signed | URL

This information will be used to display the entries to your guestbook. Now that you have created the guest book HTML form, the next step is to capture the information submitted to the guestbook by visitors. This should be the first thing done in the index.php file. Use the following algorithm to guide your efforts:

  1. Capture the information from the HTML form using ($_POST[]).
  2. If the full name OR the homepage field is blank (“”), the program should not do anything. If both the full name and the homepage field are not blank, the program should continue.
  3. Capture the current date using the date function: date("F dS, Y").
  4. Open the guest_list.txt file for append.
  5. Append the information in the file format as shown above.
  6. Close the file.

Now that you have appended the information to the file, you need to read the guest_list.txt file and output the information. You have to use the strtok() function to
delimit each of the fields so that it appears like the following:

Jim Morrison was here on August 15, 2005.

The full name field should be an active link to the person’s homepage. The guestbook
should be properly titled.  

Chapter References 

back to top

 

Copyright 2005 Albert Dieter Ritzhaupt. All Rights Reserved.