18.1. Creating or Opening a Local File

Problem

You want to open a local file to read data from it or write data to it.

Solution

Use fopen( ):

$fh = fopen('file.txt','r') or die("can't open file.txt: $php_errormsg");

Discussion

The first argument to fopen( ) is the file to open; the second argument is the mode to open the file in. The mode specifies what operations can be performed on the file (reading and/or writing), where the file pointer is placed after the file is opened (at the beginning or end of the file), whether the file is truncated to zero length after opening, and whether the file is created if it doesn’t exist, as shown in Table 18-1.

Table 18-1. fopen( ) file modes

Mode

Readable?

Writeable?

File pointer

Truncate?

Create?

r

Yes

No

Beginning

No

No

r+

Yes

Yes

Beginning

No

No

w

No

Yes

Beginning

Yes

Yes

w+

Yes

Yes

Beginning

Yes

Yes

a

No

Yes

End

No

Yes

a+

Yes

Yes

End

No

Yes

On non-POSIX systems, such as Windows, you need to add a b to the mode when opening a binary file, or reads and writes get tripped up on NUL (ASCII 0) characters:

$fh = fopen('c:/images/logo.gif','rb');

To operate on a file, pass the file handle returned from fopen( ) to other I/O functions such as fgets( ), fputs( ), and fclose( ).

If the file given to fopen( ) doesn’t have a pathname, the file is opened in the directory of the running script (web context) or in the current directory (command-line context).

You can also tell fopen( ) to search for the ...

Get PHP Cookbook 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.