Search This Blog

Monday, April 19, 2010

File and Directory Handling

Everything on your hard drive is stored as a file of one kind of another, although most folks think in terms of files and directories. There are ordinary program files, data files, files that are folders, and special files that help the hard drive keep track of the contents of folders and files. PHP has functions built in that can work with any file that can be found, but typically we'll be working with text files that contain data.
The terms directory and folder are used interchangeably in this book, and sometimes that's confusing if you aren't used to it. When you think about it, though, folders and directories hold files in an organized manner, so they both have the same function and it's not surprising that the terms are equivalent.
A file is nothing more than an ordered sequence of bytes stored on hard disk, floppy disk, CD-ROM, or other storage media. A directory is a special type of file that holds the names of other files and directories (sometimes denoted as subdirectories) and pointers to their storage area on the media. All you need to know to manipulate files and directories is how to connect your scripts to them.


There are many differences between the Linux and Windows operating systems, one of them being the way directory paths are specified. UNIX-based systems such as Linux use forward slashes to delimit elements in a path, like this:


/home/dan/data/data.txt

Windows uses backslashes:


C:\MyDocs\data\data.txt

Fortunately, PHP on Windows automatically converts the former to the latter in most situations, so something like:


$fp = fopen("/data/data.txt", "r");

shouldn't cause you any problems even if you are running the script on a Windows platform. There are some cases in which the path will be used directly (when you copy an uploaded file from the temporary directory to an archive directory, for example), in which case the backslashes are necessary. Because PHP interprets - as escaping the following character, the string will need to be specified like this:


"C:\\MyDocs\\data\\data.txt"

You'll learn an easy way to automatically convert forward slashes to backslashes in PHP later on.