introduction to web programming Getting Information About a File With stat The stat function produces useful information about files that you can use in your file management functions. The stat function returns a thirteen-element array of file information using the syntax:

open ([FILE_HANDLE_NAME], "[filename]")||
     &CgiDie ("Can't open file");
     ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size,
            $atime, $mtime, $ctime, $blksize, $blocks) =
     close ([FILE_HANDLE_NAME]);

The following table describes the elements returned by stat

Variable Description
$dev The device that the file resides on
$ino The inode for this file
$mode The permissions for the file
$nlink The number of hard links to the file
$uid The numerical user ID for the file owner
$gid The numerical group ID for the file owner
$rdev The device type if the file is a device
$size The size of the file in bytes
$atime When the file was last accessed
$mtime When the file was last modified
$ctime When the file status was last changed
$blksize The optimal block size for i/o operations on the file system containing the file
$blocks The number of clocks allocated to the file

For the most part, CGI scripts will need to take advantage only of $atime, $mtime, $ctime, $mode and $size. $size and $mode are fairly straight forward in usage. However, the usage of the "time" variables is a bit subtle.

The time values returned by stat are formatted in terms of the number of non-leap seconds since January 1, 1970, UTC. Thus, the stat function might yield a result such as $mtime is equal to "838128443". Likewise, the time function returns the current time in the same format. Thus, the scalar variable $current_time is assigned the current time with the following syntax:

     $current_time = time;

Once you have both the age of the file and the current time, you can use arithmetic to compare them for various operations such as the pruning of a Session Files directory after a certain amount of time.

For example, the following code snippet can be used to prune the file "289576893.dat" if it is older than an administratively-defined amount of time.

    $seconds_to_save = 3600;
    $age_of_file = $current_time - $mtime ;
    if ($age_of_file > $seconds_to_save)
       unlink ("289576893.dat");

If you are interested in what the actual day is, and not the number of seconds since 1970, you must use the localtime function to convert the value to a more human-recognizable form using the syntax:

($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime (time);

The following code gets the same information for an $mtime value extracted from stat:

    ($sec, $min, $hour, $mday, $mon, $year,
    $wday, $yday, $isdst) = localtime ($mtime);

Previous | Next | Table of Contents