Backend Development 4 min read

PHP stat() Function: Retrieving Detailed File Information

The PHP stat() function returns an associative array containing detailed file metadata such as size, device ID, inode, permissions, timestamps and block information, and can be used by passing a filename to retrieve and display these attributes via array keys.

php中文网 Courses
php中文网 Courses
php中文网 Courses
PHP stat() Function: Retrieving Detailed File Information

The PHP stat() function is used to obtain detailed information about a file, including its size, access time, modification time, creation time, and other attributes. It returns an associative array that holds various properties of the file.

stat() Function Syntax

<code>array stat(string $filename)</code>

Here, $filename is the path of the file whose information you want to retrieve.

Parameters and Return Value

1. Parameter Description

$filename : The file path to be inspected.

2. Return Value

Returns an associative array where each key is the name of a file attribute and the corresponding value is that attribute's value.

Attributes Returned in the Array

dev: Device ID where the file resides.

ino: Inode number of the file.

mode: File type and permissions.

nlink: Number of hard links.

uid: Owner user ID.

gid: Owner group ID.

rdev: Device ID for special files.

size: File size in bytes.

atime: Time of last access.

mtime: Time of last modification.

ctime: Time of last status change.

blksize: Preferred I/O block size for the filesystem.

blocks: Number of blocks allocated for the file.

Example Usage

<code>&lt;?php
$filename = 'test.txt';
$file_info = stat($filename);

echo 'File size: ' . $file_info['size'] . ' bytes' . PHP_EOL;
echo 'Last access time: ' . date('Y-m-d H:i:s', $file_info['atime']) . PHP_EOL;
echo 'Last modification time: ' . date('Y-m-d H:i:s', $file_info['mtime']) . PHP_EOL;
echo 'Last change time: ' . date('Y-m-d H:i:s', $file_info['ctime']) . PHP_EOL;
?&gt;</code>

This script outputs the file's size, last access time, last modification time, and last change time.

Summary

The PHP stat() function provides comprehensive file details—including size, timestamps, permissions, and more—by returning an associative array whose keys correspond to each attribute, allowing developers to easily access and display file metadata.

backendfilesystemstatfile metadata
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.