In this tutorial, we’re going to access file in PHP. And primarily we’re going to focus on this lesson in dealing with
fopen (filename, mode) so we’re going to open a file and we’re to provide a filename and we’re going to tell it what mode is should open it. And remember using “fopen” opens up a file whether it exists or not so we will create it if necessary.
At this time, we will know first how to deal with FILE ACCESS MODES:
Below are the three basic ways to open a file and the corresponding character that PHP uses. This is used to specify the intentions when you open a file.
r – it reads from the start of a file, this is just reading and it the file must exist if we’re going to read it.
W – it Truncate or Write from start, and it erases anything what is in the file that are already existing or it creates a new file if didn’t.
A – it is used to append or write to the end and these can be useful especially when we are doing a log file and we just want to add one new entry and then exit the file.
And using these modes offers an alternative version used for Reading and Writing into a file. The combination is done by placing a plus sign “+” after the file mode character.
Read/Write: r+ – it opens a file that it can be read from and written to.
Write/Read: w+ – it’s going to truncate and put it at the start but then we can go ahead and write it there.
Append: a+ – it puts us at the end of the file and also enable us to read write to the file.
At this time we’re going to create a new PHP file called “accessFile.php” and add the following code.