30.6. File Operations

As with other areas of functionality, PHP includes many functions for dealing with files. This section covers the basics of file operations and functions in PHP.

30.6.1. Opening a File

PHP uses the fopen() function for opening files. The syntax of this function is as follows:

fopen(<filename>,<mode>)

The fopen() function returns a resource pointer to the file or the value false if the file could not be opened.

The various values that can be used for <mode> are shown in the following table:

ModeMeaning
rOpen the file for reading only and place the file pointer at the beginning of the file.
r+Open the file for reading and writing and place the file pointer at the beginning of the file.
wOpen the file for writing only, zero (erase) the file if it exists, or attempt to create the file if it does not exist.
w+Open the file for reading and writing, zero (erase) the file if it exists, or attempt to create the file if it does not exist.
aOpen the file for writing only and place the file pointer at the end of the file. If the file does not exist, attempt to create it.
a+Open the file for reading and writing and place the file pointer at the end of the file. If the file does not exist, attempt to create it.
xCreate and open the file for writing only, placing the file pointer at the beginning of the file. If the file already exists, return false.
x+Create and open the file for reading and writing, placing the file pointer at the beginning of the file. If the file already exists, ...

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP 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.