13.10. Reading File Permissions and StatusIf 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.
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!"; } |