Practical WordPress Development

A Quick Tip For Reading Files with PHP

If you’re in the business of building plugins – regardless of if it’s for fun or profit – the odds that you’re eventually going to have to read the contents of a file are relatively high.

This could be for importing data from a file, this could be for parsing data out of something that a customer has provided, or this could just be used to help drive the user interface. Whatever the case, PHP offers a number of different functions for opening files and reading files.

This can be convenient, but in my experience, there’s one process that I’ve found to be more resilient than the other options when it comes to reading files and I thought I’d share the general process here.

When it comes to reading files with PHP, it’s a six step process (though a very simple set of six steps):

  1. Make sure the file exists
  2. If the file exists, then grab a resource to the file
  3. Open the file for reading
  4. Read a portion of (if not all of) the file into a variable
  5. Process the file
  6. Close access to the file

For example:

Note that there are other functions like file_get_contents which can read the entire contents of files into a variable, but in all of the work that I’ve done, using the method described above not only proves to be the most reliable when reading files, but also the most convenient (since it allows me to determine how I want to open the file – for reading, writing, how much of the file to read, etc.).

For more information, be sure to check out the fread page in the PHP manual; otherwise, I hope this method is useful in future work that you may be doing in WordPress or just in PHP in general.


  1. Scott Lesovic

    The only thing I would add is using is_readable() in place of file_exists(). That can catch some strange file permissions errors before you try to read the file itself.

    • Tom

      Ah, that’s a great tip. Hadn’t come across that before.

      Thanks for the suggestion!

  2. Timothy Brand

    I’m going to ask a scary question. I completely understand the process you posted and it looks very useful. Personally though I’ve never come across this and am having a hard time understanding, real world application, how taking a whole PHP file and storing it in a variable would work.

    I understand if this is too complex an answer for this short post or off topic, but I was just curious as I’ve never come across it before.

    • Scott Lesovic

      There are a number of cases where you would need to read a file on disk.

      Just recently, Tom posted a few articles on this site about reading and parsing CSV files. Similarly, you would need need to read an uploaded XML file to import WordPress content.

      Something I just recently did was to read in a template PDF, using PHP to apply a water mark with the purchaser’s name, then output it for the browser to download.

Leave a Reply

© 2020 Tom McFarlin

Theme by Anders NorenUp ↑