Opening and Closing Files
For most file system functions, the files have to be opened first. The function fopen() does exactly this and returns a so-called file handle, a pointer to the file. This file handle can then be used in subsequent functions to, for instance, read information from a file or write to it. fopen() expects at least two parameters:
Opening (and Closing) Files (fopen.php)<?php if ($fp = @fopen('file.txt', 'at')) { echo 'File opened.'; fclose($fp); echo '<br />File closed.'; } else { echo 'Error opening file.'; } ?> Of great interest is the file mode parameter. This is a string that consists of one or more characters. The first character is one of a, r, w, or x; after that, one or more special modifiers can be used. Table 6.1 shows all modes.
So the modifier + always adds the missing read or write access to a file mode. There are other modifiers, as well. As of PHP 4.3.2, PHP does a really good job determining whether a file is a text file or a binary file and translates funny characters appropriately. If you append b to a file mode, you force PHP to open a file as a binary file; for instance, the file mode rb opens a file for reading in binary mode. Another special modifier exists that might come in handy for Windows users: t. If this is appended to the file mode, all \n line breaks are converted into \r\n as Windows applications might expect. fopen() returns a file handle or false if opening the file did not work. You should, however, suppress any potential error messages with the @ character, or, in PHP 5, use a TRy-catch block. As soon as a file is not used anymore, it should be closed. PHP automatically closes all open files upon termination of the script; however, to use the system resources as efficiently as possible, files should be closed as early as possible to free up memory and speed up the system. For this, use fclose() and provide the file handle as a parameter. The code at the beginning of this phrase uses both fopen() and fclose(). After running the script, a file called file.txt is created.
|