O'Reilly logo

PHP in a Nutshell by Paul Hudson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 13. Files

Files can store all sorts of information. However, most file formats (e.g., picture formats such as PNG and JPEG) are binary, and very difficult and/or impossible to write using normal text techniques—in these situations, you should use the library designed to cope with each format.

One reminder: if you are using an operating system that uses backslash (\) as the path separator (e.g., Windows), you need to escape the backslash with another backslash, making (\\). Owing to this, handling files can be quite different for Windows and Unix users. Both operating systems are covered here.

Reading Files

There are several ways to open and display files, and each has its uses. You don't need to know all the ways to read files—it is probably best to learn one and stick with it for your own code. However, you will almost certainly come across each of these methods in other people's code, because everyone has her own method of getting things done.

readfile()

If you want to output a file to the screen without doing any form of text processing on it whatsoever, readfile() is the easiest function to use. When passed a filename as its only parameter, readfile() will attempt to open it, read it all into memory, then output it without further question. If successful, readfile() will return an integer equal to the number of bytes read from the file.

If unsuccessful, readfile() will return false, and there are quite a few reasons why it may fail. For example, the file might not exist, or ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required