Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

<?
$fp = fopen("log.txt", "a");


//get lock
flock($fp, 2);


//add a line to the log
fputs($fp, date("h:i A l F dS, Y\n"));


//release lock
flock($fp, 3);


fclose($fp);


//dump log
print("

");
readfile("log.txt");
print("
\n");
?>


integer fopen(string filename, string mode)


The fopen function opens a file for reading or writing. The function expects the name of
a file and a mode. It returns an integer, which is called a file handle. Internally, PHP uses
this integer to reference a block of information about the open file. The file handle is used
by other file-related functions, such as fputs and fgets.


Ordinarily, the filename argument is a path to a file. It can be fully qualified, or relative
to the path of the script. If the filename begins with http:// or ftp://, the file will be
opened using HTTP or FTP protocol over the Internet.


Table 8.6. File Read/Write Modes
Mode Operations Allowed
r[b] reading only [binary]
w[b] writing only, create if necessary, discard previous contents if any [binary]
a[b] append to file, create if necessary, start writing at end of file [binary]


Reading and Writing to Files........................................................................


w+[b]reading and writing, create if necessary, discard previous contents if any
[binary]
a+[b] reading and writing, create if necessary, start writing at end of file [binary]


The mode argument determines whether the file is to be read from, written to, or added to.
Modes with a plus sign (+) are update modes that allow both reading and writing. If the
letter b appears as the last part of the mode, the file is assumed to be a binary file, which
means no special meaning will be given to end-of-line characters. Table 8.6 lists all the
modes.

Free download pdf