Search This Blog

Monday, April 12, 2010

Chapter 7: Files and Directories

Would you like to visit a Web site in which code in the pages could take control of your hard drive and do anything its designer specified, such as write or erase files and directories? Of course not, and that's why the makers of JavaScript left those capabilities out of the language. PHP does not have the capability to write or erase files from the user's hard drive, but it can write or erase files and directories on the server. This is a good thing because often the easiest and most effective way to accomplish a particular functionality within an application is to use the server's file system.


Files are stored in folders on your hard drive (or someone else's hard drive), and because they retain their data after the machine is shut down, they are a persistent storage mechanism, instead of temporary storage such as RAM. Both directories and files are files, but directories are a special kind of file made for storing other files. Directories are created hierarchically inside other directories, starting with the root directory and proceeding down from there.


Files can contain any kind of data, and also can contain quite a bit of information about themselves, such as who owns them and when they were created. PHP makes working with the file system easy by including functions that enable you to obtain information about files, as well as open, read from, and write to them. This chapter is all about the PHP functions for working with the file system. You'll learn to read and write files with PHP, open and close files with fopen() and fclose(), rename and delete files, navigate within files, and read directory entries. You'll also see how to check file permissions and users, and accept file uploads. It's a big chapter, so let's just get started.


There are many different types of file systems; although if you're used to Windows you may not be very familiar with the others. Most Windows systems simply allow unfettered access to files and folders, whereas Linux systems typically restrict file and folder access by way of various permissions for users on the system. The NTFS file system that may be used with Windows NT/2000 and above works more like the file system on Linux machines, in that it also enables you to establish permissions.


Whether the file system uses permissions to control access to particular files and how those permissions are set are important to you as a PHP developer because some functions require specific permissions to be set before they can do their work. Fortunately, PHP also provides functions for checking and setting permissions, and for checking the access level of the current user (PHP typically runs under the authority of the same user as Apache (on Linux/Apache servers) or is provided a guest Internet account on IIS systems.