Chapter 7
- Reading and Writing to Files
|
|||||||||||||||||||
|
Chapter Topics
Basic File ProcessingFiles 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. 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:
Opening a FileBefore 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.
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. Closing a FileEvery 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.
If you do not close your file, you will likely encounter run-time errors. Remember to always close your files. Reading from a FileThe 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.
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.
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. Writing to a FileAs 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.
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.
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. 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.
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.
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. Your Seventh ProgramThis section will provide the steps for you to create your sixth PHP program.
Congratulations! You have completed the seventh chapter. You can now take the online assesement, complete the seventh activity, and move to the next chapter. Activity 7Create a PHP file named index.php with a simple
HTML form to capture the following information:
The form should action should point to the
index.php (same file) file using the POST 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:
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 Jim Morrison was here on August 15, 2005. The full name field should be an active link to
the person’s homepage. The guestbook Chapter References
|
||||||||||||||||||
|
|||||||||||||||||||