Previous Section  < Day Day Up >  Next Section

10.5 Inspecting File Permissions

As mentioned at the beginning of the chapter, your programs can only read and write files when the PHP interpreter has permission to do so. You don't have to cast about blindly and rely on error messages to figure out what those permissions are, however. PHP gives you functions with which you can determine what your program is allowed to do.

To check whether a file or directory exists, use file_exists( ). Example 10-16 uses this function to report whether a directory's index file has been created.

Example 10-16. Checking the existence of a file
if (file_exists('/usr/local/htdocs/index.html')) {

    print "Index file is there.";

} else {

    print "No index file in /usr/local/htdocs.";

}

To determine whether your program has permission to read or write a particular file, use is_readable( ) or is_writeable( ). Example 10-17 checks that a file is readable before retrieving its contents with file_get_contents( ).

Example 10-17. Testing for read permission
$template_file = 'page-template.html';

if (is_readable($template_file)) {

    $template = file_get_contents($template_file);

} else {

    print "Can't read template file.";

}

Example 10-18 verifies that a file is writable before appending a line to it with fopen( ) and fwrite( ).

Example 10-18. Testing for write permission
$log_file = '/var/log/users.log';

if (is_writeable($log_file)) {

    $fh = fopen($log_file,'ab');

    fwrite($fh, $_SESSION['username'] . ' at ' . strftime('%c') . "\n");

    fclose($fh);

} else {

    print "Cant write to log file.";

}

    Previous Section  < Day Day Up >  Next Section