O'Reilly logo

HTML, XHTML, & CSS All-in-One For Dummies®, 2nd Edition by Andy Harris

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 6. 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 function has an entire subsection in the following "Writing text to files" and "Reading from the file" 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 whether 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 the fwrite() function, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required