Inspecting File Permissions in PHP

As mentioned at the beginning of the chapter, your programs can only read and write files when the PHP engine 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 9-14 uses this function to report whether a directory’s index file has been created.

Example 9-14. 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 9-15 checks that a file is readable before retrieving its contents with file_get_contents().

$template_file = ‘page-template.html’;

if (is_readable($template_file)) {

$template = file_get_contents($template_file);

} else {

print “Can’t read template file.”;


Example 9-16 verifies that a file is writeable before appending a line to it with fopen() and fwrite().

Example 9-16. 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”);


} else {

print “Cant write to log file.”;


Source: Sklar David (2016), Learning PHP: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

Your email address will not be published. Required fields are marked *