Chapter 24. Files


The input and output in a web application usually flow between browser, server, and database, but there are many circumstances in which files are involved too. Files are useful for retrieving remote web pages for local processing, storing data without a database, and saving information to which other programs need access. Plus, as PHP becomes a tool for more than just pumping out web pages, the file I/O functions are even more useful.

PHP’s interface for file I/O is similar to that of C, although less complicated. The fundamental unit of identifying a file to read from or write to is a filehandle. This handle identifies your connection to a specific file, and you use it for operations on the file. This chapter focuses on opening and closing files and manipulating filehandles in PHP, as well as what you can do with the file contents once you’ve opened a file. Chapter 25 deals with directories and file metadata such as permissions.

This example opens /tmp/cookie-data and writes the contents of a specific cookie to the file:

$fh = fopen('/tmp/cookie-data','w')      or die("can't open file");
if (-1 == fwrite($fh,$_COOKIE['flavor'])) { die("can't write data"); }
fclose($fh)                              or die("can't close file");

The function fopen() returns a filehandle if its attempt to open the file is successful. If it can’t open the file (because of incorrect permissions, for example), it returns false and generates an E_WARNING-type error. Recipes through cover ways to open files.

Get PHP Cookbook, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.