Section 13.10. Reading File Permissions and Status


13.10. Reading File Permissions and Status

If you're sick of getting errors when you try to work with a file for which you have no permissions , there is a solution: is_readable( ) and its cousin functions, is_writeable( ), is_executable( ), is_file( ), and is_dir( ). Each takes a string as its only parameter and returns true or false. The functions work as you might expect: is_readable( ) will return true if the string parameter is readable, is_dir( ) will return false if the parameter is not a directory, etc.

For example, to check whether a file is readable:

     $filename = 'c:\boot.ini'; // Windows     $filename = '/etc/passwd'; // Unix     if (is_readable($filename)) {             print file_get_contents($filename);     } else {             print 'File not readable!';     } 

Or to check whether a file is writable:

     if (is_file($filename) && is_writeable($filename)) {             $handle = fopen($filename, "w+");             // ...[snip]...     } 

The is_readable( ) function and friends have their results cached for speed purposes. If you call is_file( ) on a filename several times in a row, PHP will calculate it the first time around then use the same value again and again in the future. If you want to clear this cached data so that PHP will have to check is_file( ) properly, you need to use the clearstatcache( ) function.

Calling clearstatcache( ) wipes PHP's file information cache, forcing it to recalculate is_file( ), is_readable( ), and such afresh. This function is, therefore, particularly useful if you are checking a file several times in a script and are aware that that file might change status during execution. It takes no parameters and returns no value.

The is_readable( ), is_writeable( ), is_executable( ), is_file( ), and is_dir( ) functions will all fail to work for remote files, as the file/directory to be examined must be local to the web server so that it can check it properly.


To read the owner of a file, use the fileowner( ) function, which takes a filename as its only parameter and returns the ID of the file's owner, like this:

     $owner = fileowner("/etc/passwd");     if ($owner != 0) {             print "Warning: /etc/passwd isn't owned by root!";     } 



PHP in a Nutshell
Ubuntu Unleashed
ISBN: 596100671
EAN: 2147483647
Year: 2003
Pages: 249

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net