O'Reilly logo

PHP Cookbook by Adam Trachtenberg, David Sklar

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 18. Files

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 C’s, although less complicated. The fundamental unit of identifying a file to read from or write to is a file handle . 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 file handles in PHP, as well as what you can do with the file contents once you’ve opened a file. Chapter 19 deals with directories and file metadata such as permissions.

Opening /tmp/cookie-data and writing the contents of a specific cookie to the file looks like this:

$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 file handle 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. Section 18.2 and Section 18.4 cover ways to open files.

The 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