Make your own free website on

Visit the Official PHP Website

Search this Site

PHP Programming

By James N Hitz

Testing Files

At one time or another you will want to test files. This is especially practical when you want to check permissions, file size, date of modification and other related file information.

SOME of the functions that we can use to test files are:

  1. file_exists()
  2. is_dir()
  3. is_file()
  4. is_writable()
  5. filetype()
  6. stat()

Except for stat(), all the other functions listed return a Boolean value (either TRUE or FALSE), and accept a filename as their only argument. Most of these are self explanatory and do not require a Ph.D. in order to comprehend. All in all, I will explain each briefly.

file_exists() tests to see if a given resides in the computer system or not. This will definitely come in handy in more than one occasions. The syntax for using the file_exists() function is:

$TrueOrFalse = file_exists("file_to_test");

The following code snippet tests to see if a file exists. We are hereby testing for the existence of a file called list.txt:

     $file2open = "/www/home/list.txt";
     if( file_exists($file2open) ){
         print "<p>The file <b>$file2open</b> exists</p>";
         print "<p>Cannot find the file <b>$file2open</b></p>.";

is_file() and is_dir() test the same thing albeit in different ways. The is_file() function tests to see whether the specified path represents a file (NOT A DIRECTORY [folder]).

is_dir() on the other hand tests whether the path specified is a directory or not.

Please note that on a Windows system you only have files and directories (even Windows shortcuts are files). On a *nix system you can have files, directories or symbolic links - fifo, char, block, link, or unknown.

To find out for sure, you may opt to use the filetype() function:

$typeOfFile = filetype("filename");

for example...

$fileType = filetype("/www/home/list.txt");

On my computer, the above path (/www/home/list.txt) represents a file so the following line of code ...

print $fileType;

...produces "file".

To test whether a file is writable, you could use the is_writable() function which like the others returns a Boolean value, and accepts the filename as the only parameter (argument).

The syntax for using the is_writable() function is:

$WritableOrNot = is_writable("file name");

Well. As you may have noticed these file testing functions are all very straightforward and easy to use - except for stat().

<< Code Explanation: Listing | The stat() function >>

JamHitz Productions