Chapter 7. Working with Files and Directories

In This Chapter

  • Saving to text files

  • Reading from text files

  • Reading a file as an array

  • Parsing delimited text data

  • Working with file and directory functions

An important part of any programming language is file manipulations. Whether you need to create a comma-separated value (CSV) file or generate a dynamic list of files in a directory, or just need a semi-permanent place to log records on the server, file manipulation functions are an indispensable part of your PHP toolbox.

Text File Manipulation

Work with text files is split into two basic categories: writing and reading. Writing and reading come down to six basic functions. See the following bullet list for a brief explanation of the six basic file functions. Each of these six functions has an entire sub-section in the following "Writing text to files" and "Reading from text files" sections:

  • fopen(): Stores a connection to a file you specify in a variable you specify

  • fwrite(): Writes text you specify to a file you specify

  • fclose(): Closes the connection to a file you specify that you created with fopen()

  • fgets(): Reads a line from a file you specify

  • feof(): Checks to see if you have hit the end of a file you specify during a file read

  • file(): Puts the entire contents of a file you specify into an array

Writing text to files

This section details the functions needed to access and write to a file, such as how to request access to a file from PHP with the fopen() function, write to the file using ...

Get HTML, XHTML, and CSS All-In-One Desk Reference For Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.