Since script 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( ). Here is an example which uses this function to report whether a directory's index file has been created.
Checking the existence of a file
<?php
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( ). Here is an example which checks that a file is readable before retrieving its contents with file_get_contents( ).
Testing for read permission
<?php
$template_file = 'page-template.html';
if (is_readable($template_file)) {
$template = file_get_contents($template_file);
} else {
print "Can't read template file.";
}
?>
Here is an example which verifies that a file is writable before appending a line to it with fopen( ) and fwrite( ).
Testing for write permission
<?php
$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.";
}
?>
- Kiran's blog
- 1176 reads













Post new comment