PHP fopen()Function


PHP Filesystem 参考手册Complete PHP Filesystem Reference Manual

Definition and Usage

The fopen() function opens a file or URL.

If fopen() fails, it returns FALSE and an error message. You can hide the error output by adding an '@' in front of the function name.

Syntax

fopen(filename,mode,include_path,context)

Parameter Description
filename Required. Specifies the file or URL to open.
mode Required. Specifies the type of access you request to the file/stream.

Possible values:

  • "r" (Open for reading only, places the file pointer at the beginning of the file)
  • "r+" (Open for reading and writing, places the file pointer at the beginning of the file)
  • "w" (Open for writing only, clears the file contents, and attempts to create the file if it does not exist)
  • "w+" (Open for reading and writing, clears the file contents, and attempts to create the file if it does not exist)
  • "a" (Open for writing only, places the file pointer at the end of the file for writing, and attempts to create the file if it does not exist)
  • "a+" (Open for reading and writing, preserves the file contents by placing the file pointer at the end of the file for writing)
  • "x" (Create a new file and open it for writing only, returns FALSE and an error if the file already exists)
  • "x+" (Create a new file and open it for reading and writing, returns FALSE and an error if the file already exists)
include_path Optional. Set this parameter to '1' if you also want to search for the file in the include_path (in php.ini).
context Optional. Specifies the environment of the file handle. context is a set of options that can modify the behavior of the stream.


Tips and Notes

Note:When writing a text file, make sure you use the correct line endings! On Unix systems, the line ending is \n; on Windows systems, the line ending is \r\n; on Macintosh systems, the line ending is \r. Windows systems provide a text conversion flag "t" that transparently converts \n to \r\n. You can also use "b" to force binary mode, so that the data will not be converted. To use these flags, use "b" or "t" as the last character of the mode parameter.


Examples

<?php
$file = fopen("test.txt","r");
$file = fopen("/home/test/test.txt","r");
$file = fopen("/home/test/test.gif","wb");
$file = fopen("http://www.example.com/","r");
$file = fopen("ftp://user:password@example.com/test.txt","w");
?>


PHP Filesystem 参考手册Complete PHP Filesystem Reference Manual Other Extensions