Retrieving a file's status

bool is_readable ( string filename)

bool is_writeable ( string filename)

bool is_executable ( string filename)

bool is_file ( string filename)

bool is_dir ( string filename)

void clearstatcache ( void )

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

Here is an example:

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

Is_readable() 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 used 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 recalculate is_file(), is_readable() and such afresh. Clearstatcache() is therefore particularly useful if you are checking a file several times in a script and are aware that that file might change status during execution. Clearstatcache() takes no parameters and returns no value.

Author's Note: is_readable(), is_writeable(), is_executable(), is_file(), and is_dir() will all fail to work for remote files, as the file/directory to be examined must be local to the web server so that it can check it properly.

 

Next chapter: Dissecting filename information >>

Previous chapter: Checking whether a file exists

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar