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 |
---|---|---|
|
|
Device |
|
|
Inode |
|
|
Permissions |
|
|
Link count |
|
|
Owner’s user ID |
|
|
Group’s group ID |
|
|
Device type for inode devices (-1 on Windows) |
|
|
Size (in bytes) |
|
|
Last access time (epoch timestamp) |
|
|
Last change time of contents (epoch timestamp) |
|
|
Last change time of contents or metadata (epoch timestamp) |
|
|
Block size for I/O (-1 on Windows) |
|
|
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.