百科狗-知识改变命运!
--

stat() - 给出文件的信息 - php 文件目录函数

百变鹏仔1年前 (2023-11-21)阅读数 19#技术干货
文章标签文件

stat()

(PHP 4, PHP 5, PHP 7)

给出文件的信息

说明

stat(string $filename): array

获取由$filename指定的文件的统计信息。如果$filename是符号连接,则统计信息是关于被连接文件本身的,而不是符号连接。

lstat()和stat()相同,只除了它会返回符号连接的状态。

参数

$filename

文件的路径。

返回值

stat()和fstat()返回格式
数字下标关联键名(自 PHP 4.0.6)说明
0devdevice number -设备名
1inoinode number - inode 号码
2modeinode protection mode - inode 保护模式
3nlinknumber of links -被连接数目
4uiduserid of owner -所有者的用户 id
5gidgroupid of owner-所有者的组 id
6rdevdevice type, if inode device *-设备类型,如果是 inode 设备的话
7sizesize in bytes -文件大小的字节数
8atimetime of last access (unix timestamp)-上次访问时间(Unix 时间戳)
9mtimetime of last modification (unix timestamp)-上次修改时间(Unix 时间戳)
10ctimetime of last change (unix timestamp)-上次改变时间(Unix 时间戳)
11blksizeblocksize of filesystem IO *-文件系统 IO 的块大小
12blocksnumber of blocks allocated -所占据块的数目
* Windows 下总是 0。

*-仅在支持 st_blksize 类型的系统下有效。其它系统(如 Windows)返回-1。

如果出错,stat()返回FALSE

Note:因为 PHP 的整数类型是有符号整型而且很多平台使用 32 位整型,对 2GB以上的文件,一些文件系统函数可能返回无法预期的结果。

错误/异常

错误时会产生E_WARNING级别的错误。

更新日志

版本说明
4.0.6返回一个数组包含有文件的统计信息,该数组具有以下列出的单元,数组下标从零开始。除了数字索引之外自还可以通过关联索引来访问。

范例

Example #1stat()例子

stat() - 给出文件的信息 - php 文件目录函数

Usingstat()information together withtouch()

注释

Note:

注意:不同文件系统对时间的判断方法可能是不相同的。

Note:此函数的结果会被缓存。参见clearstatcache()以获得更多细节。

Tip

自 PHP 5.0.0 起,此函数也用于某些URL 包装器。请参见支持的协议和封装协议以获得支持stat()系列函数功能的包装器列表。

参见

  • lstat() 给出一个文件或符号连接的信息
  • fstat() 通过已打开的文件指针取得文件信息
  • filemtime() 取得文件修改时间
  • filegroup() 取得文件的组
On GNU/Linux you can retrieve the number of currently running processes on the machine by doing a stat for hard links on the '/proc' directory like so:
$ stat -c '%h' /proc
118
You can do the same thing in php by doing a stat on /proc and grabbing the [3] 'nlink' - number of links in the returned array.
Here is the function I'm using, it does a clearstatcache() when called more than once.

get_process_count() example

The above example will output:
int(118)
Which is the number of processes that were running.
This is a souped up 'stat' function based on 
many user-submitted code snippets and 
@ http://www.askapache.com/security/chmod-stat.html 
Give it a filename, and it returns an array like stat. 

|=---------[ Example Output ]
Array(
[perms] => Array
 (
 [umask] => 0022
 [human] => -rw-r--r--
 [octal1] => 644
 [octal2] => 0644
 [decimal] => 100644
 [fileperms] => 33188
 [mode1] => 33188
 [mode2] => 33188
 )
 
[filetype] => Array
 (
 [type] => file
 [type_octal] => 0100000
 [is_file] => 1
 [is_dir] =>
 [is_link] =>
 [is_readable] => 1
 [is_writable] => 1
 )
 
[owner] => Array
 (
 [fileowner] => 035483
 [filegroup] => 23472
 [owner_name] => askapache
 [group_name] => grp22558
 )
 
[file] => Array
 (
 [filename] => /home/askapache/askapache-stat/htdocs/ok/g.php
 [realpath] =>
 [dirname] => /home/askapache/askapache-stat/htdocs/ok
 [basename] => g.php
 )
 
[device] => Array
 (
 [device] => 25
 [device_number] => 0
 [inode] => 92455020
 [link_count] => 1
 [link_to] =>
 )
 
[size] => Array
 (
 [size] => 2652
 [blocks] => 8
 [block_size] => 8192
 )
 
[time] => Array
 (
 [mtime] => 1227685253
 [atime] => 1227685138
 [ctime] => 1227685253
 [accessed] => 2008 Nov Tue 23:38:58
 [modified] => 2008 Nov Tue 23:40:53
 [created] => 2008 Nov Tue 23:40:53
 )
)
If you want to know a directory size, this function will help you: 
If you have ftp (and the related sftp) protocols disabled on your remote server, it can be hard figuring out how to 'stat' a remote file. The following works for me: 
There's an important (yet little-known) problem with file dates on Windows and Daylight Savings. This affects the 'atime' and 'mtime' elements returned by stat(), and it also affects other filesystem-related functions such as fileatime() and filemtime().
During the winter months (when Daylight Savings isn't in effect), Windows will report a certain timestamp for a given file. However, when summer comes and Daylight Savings starts, Windows will report a DIFFERENT timestamp! Even if the file hasn't been altered at all, Windows will shift every timestamp it reads forward one full hour during Daylight Savings.
This all stems from the fact that M$ decided to use a hackneyed method of tracking file dates to make sure there are no ambiguous times during the "repeated hour" when DST ends in October, maintain compatibility with older FAT partitions, etc. An excellent description of what/why this is can be found at http://www.codeproject.com/datetime/dstbugs.asp
This is noteworthy because *nix platforms don't have this problem. This could introduce some hard-to-track bugs if you're trying to move scripts that track file timestamps between platforms.
I spent a fair amount of time trying to debug one of my own scripts that was suffering from this problem. I was storing file modification times in a MySQL table, then using that information to see which files had been altered since the last run of the script. After each Daylight Savings change, every single file the script saw was considered "changed" since the last run, since all the timestamps were off by +/- 3600 seconds.
This one-liner is probably one of the most incorrect fixes that could ever be devised, but it's worked flawlessly in production-grade environments... Assuming $file_date is a Unix timestamp you've just read from a file:

That will ensure that the timestamp you're working with is always consistently reported, regardless of whether the machine is in Daylight Savings or not.
I was curious how I could tell if a file was a directory... so I found on http://www.hmug.org/man/2/stat.html the following information about the mode bits:
#define S_IFMT 0170000      /* type of file */
#define    S_IFIFO 0010000 /* named pipe (fifo) */
#define    S_IFCHR 0020000 /* character special */
#define    S_IFDIR 0040000 /* directory */
#define    S_IFBLK 0060000 /* block special */
#define    S_IFREG 0100000 /* regular */
#define    S_IFLNK 0120000 /* symbolic link */
#define    S_IFSOCK 0140000 /* socket */
#define    S_IFWHT 0160000 /* whiteout */
#define S_ISUID 0004000 /* set user id on execution */
#define S_ISGID 0002000 /* set group id on execution */
#define S_ISVTX 0001000 /* save swapped text even after use */
#define S_IRUSR 0000400 /* read permission, owner */
#define S_IWUSR 0000200 /* write permission, owner */
#define S_IXUSR 0000100 /* execute/search permission, owner */
Note that these numbers are in octal format. Then, to check to see if the file is a directory, after calling fstat, I do:
if ($fstats[mode] & 040000)
 ... this must be a directory
To the note of how you can figure out if a file is a folder or not, there is also the handy "is_dir" function.
Regarding the stat() on files larger than 2GB on 32 bit systems not working, note that the behavior appears to differ between Linux and Windows. Under Windows there's so way to know whether or not this failed.
It's been my experience that under Linux, performing a stat() on files that are too large for the integer size generates a warning and returns false. However under Windows it silently truncates the high order bits of the size resulting in an incorrect number. The only way you'd ever know it failed is in the event that the truncation happened to leave the sign bit on resulting in a negative size. That is, there is _no_ reliable way to know it failed.
This is true of filesize() as well.
Tom
In response to the note whose first line is:
Re note posted by "admin at smitelli dot com"
I believe you have the conversion backwards. You should add an hour to filemtime if the system is in DST and the file is not. Conversely, you should subtract an hour if the file time is DST and the current OS time is not.
Here's a simplified, corrected version:

Here's a test:

Output:
------------------------------
(when run in summer)
------------------------------
Date0 (ST): Tuesday, 01-Jan-08 10:00:00 EST
Date1 (DT): Friday, 01-Aug-08 10:00:00 EDT
Uncorrected: 
File 0: -3600
File 1: 0
Corrected: 
File 0: 0
File 1: 0
------------------------------
(when run in winter--dates omitted)
------------------------------
Uncorrected: 
File 0: 0
File 1: 3600
Corrected: 
File 0: 0
File 1: 0
In response to Re note posted by "admin at smitelli dot com", your version below gives the following output when substituted into my test:
------------------------------
(when run in summer--dates omitted)
------------------------------
Uncorrected: 
File 0: -3600
File 1: 0
Corrected: 
File 0: -7200
File 1: 0
------------------------------
You can see that the operation is the opposite of what it should be.
Here's what the UNIX man page on stat has to say about the difference between a file change and a file modification:
st_mtime Time when data was last modified. Changed by the following functions:  creat(), mknod(), pipe(), utime(), and write(2).
st_ctime Time when file status was last changed.  Changed by the following functions: chmod(), chown(), creat(), link(2), mknod(), pipe(), unlink(2), utime(), and write().
So a modification is a change in the data, whereas a change also happens if you modify file permissions and so on.
stat() may not work on mounted CIFS' in 32 bit systems if you do not specify the option noserverino when mounting. E.g:
mount -t cifs -o user="user",password="password",noserverino //example.local/share /mnt/mount-point
Other functions based on stat() data such as file time functions and is_dir() are affected the same way.
This happens because if you do not specify the option noserverino the remote inode may be 64 bit-based and thus the local system cannot handle it.
Re note posted by "salisbm at hotmail dot com":
S_IFDIR is not a single-bit flag. It is a constant that relies on the "S_IFMT" bitmask. This bitmask should be applied to the "mode" parameter before comparing with any of the other "S_IF..." constants, as indicated by stat.h:
#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
That is, this approach is incorrect:

...and should instead be:

As pointed out by "svend at svendtofte dot com", however, there is also the "is_dir" function for this purpose, along with "is_file" and "is_link" to cover the most common format types...
The dir_size function provided by "marting.dc AT gmail.com" works great, except the $mas variable is not initialized. Add:
  $mas = 0;
before the while() loop.
To ignore index number or name specifics.. use:
list($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks)
     = lstat($directory_element);
Re note posted by "admin at smitelli dot com"
I'm not sure how that can work all year round since you have to modify both opposing inside and outside DST based on the actual files themselves, as well as the current DST setting for the system.
e.g. using filemtime, same thing for stat.

Just another example of why 'not' to use windows in a server room.
If the 2GB limit is driving you crazy, you can use this complete hack. use in place of filesize()
function file_size($file) {
 $size = filesize($file);
 if ( $size == 0)
  $size = exec("ls -l $file | awk '{print $5}'");
 return $size;
}
is identical to:

at least on my linux box.

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)