Chapter 9. Working with Files
The data storage destination of choice for a web application is a database. That doesn’t mean that you’re completely off the hook from dealing with regular old files, though. Plain text files are still a handy, universal way to exchange some kinds of information.
You can do easy customization of your website by storing HTML templates in text files. When it’s time to generate a specialized page, load the text file, substitute real data for the template elements, and print it. Example 9-2 shows you how to do this.
Files are also good for exchanging tabular data between your program and a spreadsheet. In your PHP programs, you can easily read and write the CSV (comma-separated value) files with which spreadsheet programs work.
This chapter shows you how to work with files from your PHP programs: dealing with file permissions, which your computer uses to enforces rules about which files your programs can read and write; reading data from and writing data to files; and handling errors that may occur with file-related operations.
Understanding File Permissions
To read or write a file with any of the functions you’ll learn about in this chapter, the PHP engine must have permission from the operating system to do so. Every program that runs on a computer, including the PHP engine, runs with the privileges of a particular user account. Most of the user accounts correspond to people. When you log in to your computer and start up your word processor, that word ...