Page 351 - Beginning PHP 5.3
P. 351
Chapter 11: Working with Files and Directories
Permissions generally won ’ t affect you much when writing PHP scripts, because PHP usually does the
right thing behind the scenes. For example, if you create a new file for writing, PHP automatically gives
that file read and write permission for the user that ’ s running your PHP script (usually the Web server
user). If you create a new directory, PHP gives the directory read, write, and execute permission for all
users by default, meaning that anyone can create and delete files within that directory.
In this section you explore PHP ’ s chmod() function, which lets you change the mode (permissions) of a
file or directory. You also take a look at three PHP functions that let you determine if a file or directory is
readable, writable, or executable by the current user.
Changing Permissions
PHP ’ s chmod() function is used to change the mode, or permissions, of a file or directory. It functions
much like the UNIX chmod command.
This section applies mainly to UNIX - based Web servers such as Linux and Mac OS X. Windows
servers do not have a concept of file and directory modes. Instead, you use Windows Explorer to set
access permissions on files and folders by right - clicking the item, choosing Properties, then clicking the
Security tab. You need to be an administrator to make these changes. If you ’ re running your PHP
scripts on a shared Windows server, and you need to set permissions on a certain file or folder, ask your
hosting company for help. Often they ’ ll do it for you, or point you to a Web - based control panel where
you can do it yourself.
To change a file ’ s permissions with chmod() , pass it the filename and the new mode to use.
For example, to set a file ’ s mode to 644, use:
chmod( “myfile.txt”, 0644 );
The 0 (zero) before the 644 is important, because it tells PHP to interpret the digits as an octal number.
chmod() returns true if the permission change was successful, and false if it failed (for example,
you ’ re not the owner of the file).
So how do file modes work? Here ’ s a quick primer.
File modes are usually expressed as octal numbers containing three digits. The first digit determines
what the file ’ s owner – – usually the user that created the file — can do with the file. The second digit
determines what users in the file ’ s group — again, usually the group of the user that created the file —
can do with it. Finally, the last digit dictates what everyone else can do with the file.
The value of each digit represents the access permission for that particular class of user, as follows:
Digit Value Permission
0 Cannot read, write to, or execute the file
1 Can only execute the file
2 Can only write to the file
313
9/21/09 9:10:16 AM
c11.indd 313
c11.indd 313 9/21/09 9:10:16 AM