19.2. Getting File Information

Problem

You want to read a file’s metadata; for example, permissions and ownership.

Solution

Use stat( ) , which returns an array of information about a file:

$info = stat('harpo.php');

Discussion

The function stat( ) returns an array with both numeric and string indexes with information about a file. The elements of this array are in Table 19-3.

Table 19-3. Information returned by stat( )

Numeric index

String index

Value

0

dev

Device

1

ino

Inode

2

mode

Permissions

3

nlink

Link count

4

uid

Owner’s user ID

5

gid

Group’s group ID

6

rdev

Device type for inode devices (-1 on Windows)

7

size

Size (in bytes)

8

atime

Last access time (epoch timestamp)

9

mtime

Last change time of contents (epoch timestamp)

10

ctime

Last change time of contents or metadata (epoch timestamp)

11

blksize

Block size for I/O (-1 on Windows)

12

blocks

Number of block allocated to this file

The mode element of the returned array contains the permissions expressed as a base 10 integer. This is confusing since permissions are usually either expressed symbolically (e.g., ls’s -rw-r--r-- output) or as an octal integer (e.g., 0644). To convert the permissions to a more understandable format, use base_convert( ) to change the permissions to octal:

$file_info = stat('/tmp/session.txt');
$permissions = base_convert($file_info['mode'],10,8);

This results in a six-digit octal number. For example, ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.