Files

There are many times where a developer needs to access different files on the server. You might want to read or write to some text or XML file for one reason or another. I highly recommend trying to use databases before using files to store data, but sometimes there are a few good reasons to use files. PHP file handling is very powerful stuff, so I have broken this up into a few sections. Let’s see the basics of opening and closing a file.

Example

Nothing to special here. We simply call fopen with our file location, which is sampleFile.txt, and then we specify the mode, which is r for read here. PHP just needs to know where the file is, the file’s name, and what we plan to do with it. Since I just have the file name, PHP assumes that the file is in the same directory as the file with this example code. The next section of this tutorial will cover how we tell PHP what we want to do with the file.

File Open Modes

PHP requires us to tell it what we would like to do with the file we are about to open before we open it. It needs to know these things for a few reasons. The main reason is PHP needs to know what permission it needs to do what you want with the file. If the file has read only access, PHP would like for you to only ask it to read the file because writing to the file will make PHP and the server grumpy. There are 6 important modes in the file opening process.

  • r – read only from the beginning of the file
  • r+ – read and/or write only from the beginning of the file
  • w – clears file’s contents and writes to the file from the beginning (Creates a new file if it doesn’t exist)
  • w+ – clears file’s contents and read/write to the file from the beginning (Creates a new file if it doesn’t exist)
  • a – appends to file’s existing content (Creates a new file if it doesn’t exist)
  • a+ – appends to or reads file’s existing content (Creates a new file if it doesn’t exist)

With every file that we open, we should always close it. So, let’s do just that.

Example

This example is just like the previous example, except for the bottom line. The fclose is our way to tell PHP we are done with the file and that it can be closed. It only has one parameter, which is the name of the file variable. Simple enough? I think PHP does a great job with memory management, but you should always close your files just to be extra sure you don’t create huge memory leaks. Let’s move onto doing stuff with the file.

If you enjoyed this resource, support me by sharing this page with others.
Share on Facebook
Facebook
Share on Google+
Google+
Share on StumbleUpon
StumbleUpon
Digg this
Digg
Tweet about this on Twitter
Twitter
Share on Reddit
Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *