How To Check For A File In PHP (And Get Useful File Info)

Sometimes you may need to just simply check if a file exists from within your code, without having to open it or do anything else. Sure, you could just open it and see if it was successful, or do something more ugly like open a shell and do an ls for it (yuck!). But, a more elegant way to check a file's status is to use stat().

You can use stat() in the following way which will return true or false, if the file has been found or not:

function check_file( $file ){
    if ( stat( $file ) ){
        return true;
    }
    else {
        return false
    }
}

What this function will do is simply return 1, or TRUE if the stat was successful. You can then check for a true or false status to find out if your file exists. This is useful in the event of alerting a user of an improper file location or to simply add a level of safety before attempting to open a file handle.

The stat function will also return a bunch of other useful stuff for you to use. If prepending a variable to the command, you can get an array of values for different attributes of the file:

$file_attributes = stat( '/home/users/foo/my_foo_file.txt' );

The variable $file_attributes is an array containing information for the following:

0 dev device number
1 ino inode number *
2 mode inode protection mode
3 nlink number of links
4 uid userid of owner *
5 gid groupid of owner *
6 rdev device type, if inode device
7 size size in bytes
8 atime time of last access (Unix timestamp)
9 mtime time of last modification (Unix timestamp)
10 ctime time of last inode change (Unix timestamp)
11 blksize blocksize of filesystem IO **
12 blocks number of blocks allocated **


Probably the most useful information for most users here is the uid, gid, size, atime, and mtime. These are the user id and group id on the OS, the file size in bytes, the last time the file was accessed and the last time it was modified (Windows results may vary ~). They are available in the order they appear in the table above in the array, e.g. $file_attributes[7] will show you the file size.

For more, go here