PHP fopen() Function
Definition
The fopen() function opens a file or URL.
fopen() is lifted straight from C,
Syntax
PHP fopen() Function has the following syntax.
fopen(filename,mode,include_path,context)
Parameter
Parameter | Is required | Description |
---|---|---|
filename | Required. | File or URL to open |
mode | Required. | Type of access you require to the file/stream. |
include_path | Optional. | Set to '1' to search for the file in the include_path in php.ini |
context | Optional. | Context of the file handle. |
Possible values for mode:
Mode | Meaning | Note |
---|---|---|
"r" | Read only. | Starts at the beginning of the file |
"r+" | Read/Write. | Starts at the beginning of the file |
"w" | Write only. | Opens and clears the contents of file; or creates a new file if it doesn't exist |
"w+" | Read/Write. | Opens and clears the contents of file; or creates a new file if it doesn't exist |
"a" | Write only. | Opens and writes to the end of the file or creates a new file if it doesn't exist |
"a+" | Read/Write. | Preserves file content by writing to the end of the file |
"x" | Write only. | Creates a new file. Returns FALSE and an error if file already exists |
"x+" | Read/Write. | Creates a new file. Returns FALSE and an error if file already exists |
Return
Returns a file pointer resource on success, or FALSE on error.
We can hide the error output by adding an '@' in front of the function name.
Example 1
Take a look at the following usages:
$file1 = fopen("file.txt", "r") OR die ("Can't open file!\n");
$file2= fopen("$logFileName", "w") OR die ("Log file not writeable!\n");
The fopen() function returns a file handle resource. You should store the return value of fopen() in a variable for later use:
<?PHP// w w w .ja v a 2 s. c o m
$filename = "c:/abc/test.txt";
$handle = fopen($filename, "a");
if (!$handle) {
print "Failed to open $filename for appending.\n";
}
?>
Example 2
The fopen() can specify remote files. PHP automatically opens a HTTP/FTP connection for you, returning the file handle.
This example displays the google web site through your browser:
<?PHP/* ww w .j a v a 2 s . com*/
$google = fopen("http://www.google.org", "r");
$site = fread($google, 200000);
fclose($google);
print $site;
?>
The r mode is specified because web servers do not allow writing through HTTP,
$file = fopen("http://www.example.com/","r");
$file = fopen("ftp://user:password@example.com/test.txt","w");
The code above generates the following result.