Test directory permissions
Posted: Sat Jun 23, 2007 11:48 am
It seems that directory permissions seems to be the bane of any application that wants to write to the filesystem. I have written a short little function that not only checks if a directory is writable by the script, but will give friendly error messages on how to fix file permissions if we can't write.
Comments?
Comments?
Code: Select all
/**
* Tests permissions on a directory and throws out friendly
* error messages and attempts to chmod it itself if possible
*/
function _testPermissions($dir) {
// early abort, if it is writable, everything is hunky-dory
if (is_writable($dir)) return true;
if (!is_dir($dir)) {
// generally, you'll want to handle this beforehand
// so a more specific error message can be given
trigger_error('Directory '.$dir.' does not exist',
E_USER_ERROR);
return false;
}
if (function_exists('posix_getuid')) {
// POSIX system, we can give more specific advice
if (fileowner($dir) === posix_getuid()) {
// we can chmod it ourselves
chmod($dir, 0755);
return true;
} elseif (filegroup($dir) === posix_getgid()) {
$chmod = '775';
} else {
// PHP's probably running as nobody, so we'll
// need to give global permissions
$chmod = '777';
}
trigger_error('Directory '.$dir.' not writable, '.
'please chmod to ' . $chmod,
E_USER_ERROR);
} else {
// generic error message
trigger_error('Directory '.$dir.' not writable, '.
'please alter file permissions',
E_USER_ERROR);
}
return false;
}