|
| HOW TO OPEN FILES WITH PHP USING THE fopen() FUNCTION
Before you can peform any read or write action on files on your server with PHP, you need to open them first.
The general format for opening a file with PHP is as follows:
$fh = fopen ("filename", "mode");
PHP needs you to specify the opening mode which is based on what you intend doing with that file once it's opened.
PHP provides you options of the following modes:
r
Read only.
r+
Reading and writing.
w
Write only.
w+
Reading and writing.
a
Append new data to end of file contents.
a+
Reading and appending new data to end of file contents.
You will need to choose the mode depending on what you want to do with the files once opened.
The variable $fh is referred to as a file handle that PHP uses to keep information of the location of the file. You can use any name for this variable but $fh is commonly used.
Opening a file in read mode
You will use this option if you only want PHP to read from a file once opened.
$fh=fopen ("thefile.txt", "r");
PHP will then look for the file in the current directory that this file open script is in. If it finds the file, it opens it. If it doesn't, it issues a warning saying that the file does not exist.
Opening a file in write mode
You will use this option if you only want PHP to write actions on a file once opened.
$fh=fopen ("thefile.txt", "w");
PHP will then look for the file in the current directory that this file open script is in. If it finds the file, it opens it. If it doesn't, it automatically creates this file.
You can also open a url with the fopen() function as follows:
$fh=fopen ("http://www.somesite.com/somepage.html", "r");
Also note that you can only open a url in read mode and not write mode.
Once you have opened a file and performed whatever actions you need, you can close that file as follows:
fclose($fh);
 |
|
|