Checking File Permissions In PHP

0
Your rating: None

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.";

}
?>

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.

Cumulus Tag Cloud

Kiran Says

SEO Architect,SEO Specialist reflect my values.

By enduring black hat methods the SEO industry is setting itself up for washout and sleepwalking into oblivion.

Jobs in India