6.5 Opening a File


You want to open a file. This can be useful in a plethora of ways, including saving form results, reading records, storing records, and printing files.

Technique

Use fopen() to open a file and assign the pointer to a variable:

 <?php $fp = @fopen ("somefile.src", "r") or   die("Could not open somefile.src for read access"); ?> 

Comments

The fopen() function opens a pointer to the file on the filesystem. You can then work with that pointer with the following functions: fclose() , feof() , fgetc () , fgetcsv() , fgets() , fgetss() , flock () , fpassthru() , fputs() , fread() , fseek() , ftell () , and fwrite() .

The first argument of fopen() is the file to be opened. It can be a local file, a Web address (must start with http:// and trailing slashes must be provided), or an FTP server (must start with ftp:// ). The second argument of fopen() is the mode in which you want to open the file. In this case, we open the file for read access. The following is a table of the codes that you can use to open a file and their corresponding modes.

Code Mode
"r" Open with read access; file pointer is at the beginning of the file.
"r+" Open with read and write access; file pointer is at the beginning of the file.
"w" -Open with write access; file pointer at the beginning of the file. If the file exists, delete its contents. If the file does not exist, create it.
"w+" -Open with read and write access; file pointer at the beginning of the file. If the file exists, delete its contents. If the file does not exist, create it.
"a" -Open with write access; file pointer at the end of the file. If the file does not exist, create it.
"a+" -Open with read and write access; file pointer at the end of file. If the file does not exist, create it.

Note

Appending a "b" to any of these codes will tell PHP that the file is binary. (This is useless on UNIX, but needed on systems such as Windows where there is a difference between binary and ASCII files.) Also, you cannot use any other mode besides the "r" mode when opening Web addresses or when connecting to FTP servers.


fopen() is just one way to open a file. You can also use the file() function to open a file and return an array of lines like the following, which prints out a file line-by-line :

 <?php $f_contents = file('somefile.src'); foreach ($f_contents as $line) {     print $line; } ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

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