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.
<?php //specify the filename and we call it as hello.txt $testfile = 'hello.txt'; //and inside the if statement, we pass the $testfile variable to fopen and we specify the mode as write //and fopen return a handle as a value, and using handle is useful because we could close it //close the handle }else{ //if the file can't be open..and it can prevent some error might happen echo 'Could not open the file'; } ?>