Recipe 23.1. Creating or Opening a Local File


23.1.1. Problem

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

23.1.2. Solution

Use fopen( ), as in Example 23-7.

Opening a file

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

23.1.3. Discussion

The first argument to fopen( ) is the file to open; the second argument is the mode in which to open the file. 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 23-1.

Table 23-1. fopen( ) file modes

Mode

Readable?

Writable?

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

x

No

Yes

Beginning

No

Yes

x+

Yes

Yes

Beginning

No

Yes


The x and x+ modes return false and generate a warning if the file already exists. They are available in PHP 4.3.2 and later.

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

Safely reading a binary file

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

Even though Unix systems handle binary files fine without the b in the mode, it's a good idea to use it always. That way, your code is maximally portable and runs well on both Unix and Windows.

To operate on a file, pass the filehandle 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 file to open in the include_path specified in your php.ini file by passing true as a third argument. Example 23-9 searches for file.inc in the include_path.

Opening files in the include_path

<?php $fh = fopen('file.inc','r',true) or die("can't open file.inc: $php_errormsg"); ?>

23.1.4. See Also

Documentation on fopen( ) at http://www.php.net/fopen.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net