php to Open a File with fopen()

The fopen() function opens a file and returns a file handle associated with the file

The first argument passed to fopen() specifies the name of the file you want to open, and the second argument specifies the mode , or how the file is to be used

For example:

$handle = fopen( “data.txt”, “r” );

The first argument can be just a filename ( “ data.txt “ ), in which case PHP will look for the file in the current directory

The second argument to fopen() tells PHP how you’re going to use the file. It can take one of the following string values

ValueDescription
rOpen the file for reading only. The file pointer is placed at the beginning of the file
r+Open the file for reading and writing. The file pointer is placed at the beginning of the file
wOpen the file for writing only. Any existing content will be lost. If the file does not exist, PHP
attempts to create it
aOpen the file for appending only. Data is written to the end of an existing file. If the file does
not exist, PHP attempts to create it
a+Open the file for reading and appending. Data is written to the end of an existing file. If the file does not exist, PHP attempts to create it.
fopen second parameters

Example of fopen in php

<?php
$handle = fopen("c:\\folder\\resource.txt", "r");
?>
<?php
$handle = fopen("/home/rasmus/file.txt", "r");
$handle = fopen("/home/rasmus/file.gif", "wb");
$handle = fopen("http://www.example.com/", "r");
$handle = fopen("ftp://user:password@example.com/somefile.txt", "w");
?>

Leave a Comment