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, ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.