When you open a file in PHP one of the first things you have to think about is what mode do you wish to open the file, Do you want to create a new file, Do you wish to open an existing file and add more data or do you wish to read data from an existing file. Some of the most common modes are displayed below.
Modes
"r" opens a file for reading only, the file pointer is at the beginning of the file
"r+" opens a file for reading/writing, file pointer is at the beginning of the file
"w" opens and clears file for writing only, if file does not exist it is created
"w+" Write/Read opens and clears the contents of the file, if file does not exist it is created
"a" append,
Opens and writes to the end of the file or creates a new file if
it does not exist
"a+" is Read/Append mode, writes to the end of the file
"x" will create a new file but it will return an error if the file already exists
"x+" Read/Write
will create a new file but it will return an error if the file already exists
Lets look at some examples
Firstly we wish to open a file called myfile.txt for reading.
$file = fopen("myfile.txt","r") or die("Cannot open the file");
$fclose($file);
Our second example we will write to an existing file called testfile.txt
$file = fopen("testfile.txt","w") or die("Cannot open the file");
$fclose($file);
As you can see there are different ways to open files and whichever way you choose is dependent on what you wish to do with your script. An important thing to remember is if you already have data in a file and wish to keep it use the "a" or "a+" mode, a common gotcha is to clear the existing data by using the wrong mode.
|