Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Reading File Permissions and Status

If you're sick of getting errors when you try to work with a file for which you have no permissions , there is a solution: is_readable() and its cousin functions, is_writeable(), is_executable(), is_file(), and is_dir(). Each takes a string as its only parameter and returns true or false. The functions work as you might expect: is_readable() will return true if the string parameter is readable, is_dir() will return false if the parameter is not a directory, etc.

For example, to check whether a file is readable:

    $filename = 'c:\boot.ini'; // Windows
    $filename = '/etc/passwd'; // Unix

    if (is_readable($filename)) {
            print file_get_contents($filename);
    } else {
            print 'File not readable!';
    }

Or to check whether a file is writable:

    if (is_file($filename) && is_writeable($filename)) {
            $handle = fopen($filename, "w+");
            // ...[snip]...
    }

The is_readable() function and friends have their results cached for speed purposes. If you call is_file() on a filename several times in a row, PHP will calculate it the first time around then use the same value again and again in the future. If you want to clear this cached data so that PHP will have to check is_file() properly, you need to use the clearstatcache() function.

Calling clearstatcache() wipes PHP's file information cache, forcing it to recalculate is_file(), is_readable(), and such afresh. This function is, therefore, particularly useful if you are checking a file several times in a script and are aware that ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page