PHP File Handling: Accessing File

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.
  1. <?php
  2. //specify the filename and we call it as hello.txt
  3. $testfile = 'hello.txt';
  4. //and inside the if statement, we pass the $testfile variable to fopen and we specify the mode as write
  5. //and fopen return a handle as a value, and using handle is useful because we could close it
  6. if($fh = fopen($testfile, 'w')){
  7. //close the handle
  8. fclose($fh);
  9. }else{
  10. //if the file can't be open..and it can prevent some error might happen
  11. echo 'Could not open the file';
  12. }
  14. ?>
After executing the code above, as expected it will create a new file in our document root. And it looks like as shown below.

Add new comment