Chapter 23. Files

23.0. Introduction

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 that other programs need access to. 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 24 deals with directories and file metadata such as permissions.

The code in Example 23-1 opens /tmp/cookie-data and writes the contents of a specific cookie to the file.

Example 23-1. Writing data to a file
<?php
$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 ...

Get PHP Cookbook, 2nd Edition 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.