Reading files

There are three distinct ways to open and display files, and we will be looking at all of them - each have their uses. The simplest possible way is to call readfile(), which takes a filename as its first parameter and simply opens the file, outputs it to the screen, then closes it. Sadly, it's very rare you just want to print a file's contents to the screen, which makes this function rather rare.

A slightly more complicated way, but equally more powerful, is to use the file_get_contents() function, which loads the file specified as the first parameter and returns it as a string. This function is the most common, because it's just so easy to use. The last way, using the fopen() function, is the most complicated and also the most powerful - indeed, it's so powerful that few people really need to use it!

Author's Note: you don't need to know all three ways to read files - indeed, it is probably best to learn one and stick with it for your own code. However, having said that, you will almost certainly come across each of these three methods in other people's code, because everyone has their own method of getting things done. My advice to you is to learn all three, at least as far as knowing what they do, and learn one specific way for your own use. That way, at least you have got a vague idea when you see other code, and you know that you can look back here or in the PHP manual if you get stuck.

If you're interested, I use file_get_contents() 99% of the time. In fact, I can't remember the last time I used either fopen() or readfile()!


Next chapter: readfile() >>

Previous chapter: Files

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.