PHP » I/O » fopen()

Syntax:
int fopen(string filename, string mode [, bool use_include_path [, resource context]])
filename
The file to open.
mode
Whether the file should be opened for reading or writing etc.
use_include_path
Whether to look for the file in the include path.
context
Stream context to use.

Opens a file.

The fopen() function opens a file and returns a handle for it. The filename is not limited to the local filesystem. Prepending the file name with file:// will point to the local filesystem, but this is the default and can be omitted. Protocols like ftp:// and http:// can also be used, as well as Samba/Windows shares with the double slash notation: //windowsserver/share/file.txt.

The optional use_include_path parameter tells fopen() whether to look for the file in the include path in addition to the current directory. Contexts can be used to modify the file stream, but are outside the scope of this manual.

The file can be opened using the different modes listed below. In addition, "b" can be added to open the file in binary mode. By default, files are opened in text mode, which means that PHP pays attention to new line characters.

ModeDescription
rReading only
wWriting only. The file will be created if necessary.
r+Reading and writing.
w+Reading and writing. The file will be created if necessary.
aAppend to file. The file will be created if necessary.
a+Read and writing. File pointer will start at the end of the file. The file will be created if necessary.


If the call fails, FALSE is returned.

Examples

Code:
<?php

print "Writing to logfile... ";
$logfile = fopen("log.txt", "a");
fputs($logfile, "Sample code running\n");
fclose($logfile);
print "Done.";

?>
Output:
Writing to logfile... Done.
Explanation:

This code puts a line in a logfile each time it is run. The "a" mode makes sure that the data is written to the end of the file each time.

See Also: