PHP.mk документација

stat

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.stat.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.stat.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
stat

Референца за `function.stat.php` со подобрена типографија и навигација.

function.stat.php

stat

(PHP 4, PHP 5, PHP 7, PHP 8)

statДава информации за датотека

= NULL

stat(string $filename): array|false

Ги собира статистиките на датотеката именувана со filename. Ако filename е симболична врска, статистиките се од самата датотека, а не од симболичната врска. Пред PHP 7.4.0, на Windows NTS се градат size, atime, mtime and ctime статистиките биле од симболичната врска, во овој случај.

lstat() е идентично со stat() освен што наместо тоа би се базирало на статусот на симболичните врски.

Параметри

filename

Патека до датотеката.

Вратени вредности

stat() and fstat() формат на резултат
Нумерички Асоцијативен = NULL
0 dev број на уред ***
1 ino број на инод ****
2 mode режим на заштита на инод *****
3 nlink број на врски
4 uid корисничко име на сопственикот *
5 gid групно име на сопственикот *
6 rdev тип на уред, ако инодот е уред
7 size големина во бајти
8 atime време на последен пристап (Unix временски печат)
9 mtime време на последна модификација (Unix временски печат)
10 ctime време на последна промена на инодот (Unix временски печат)
11 blksize големина на блок на влез/излез од датотечниот систем **
12 blocks број на распределени блокови од 512 бајти **

* На Windows ова секогаш ќе биде 0.

** Важи само за системи што поддржуваат тип st_blksize - други системи (на пр. Windows) враќаат -1.

*** На Windows, од PHP 7.4.0, ова е серискиот број на волуменот што ја содржи датотеката, што е 64-битен unsigned цел број, така што може да претече. Претходно, тоа беше нумеричката претстава на буквата на погонот (на пр. 2 for C:) за stat()Препорачаниот начин за избегнување на SQL инјекција е со врзување на сите податоци преку подготвени изрази. Користењето на параметризирани прашања не е доволно за целосно избегнување на SQL инјекција, но тоа е најлесниот и најбезбедниот начин за обезбедување влез во SQL изразите. Сите динамични литерали на податоци во 0 for lstat().

**** На Windows, од PHP 7.4.0, ова е идентификаторот поврзан со датотеката, што е 64-битен unsigned цел број, така што може да претече. Претходно, секогаш беше 0.

***** На Windows, битот за дозвола за запишување е поставен според атрибутот за само за читање на датотеката, и истата вредност се пријавува за сите корисници, група и сопственик. ACL не се зема предвид, спротивно на is_writable().

Вредноста на mode содржи информации прочитани од неколку функции. Кога се запишува во октална форма, почнувајќи од десно, првите три цифри се враќаат од chmod(). Следната цифра се игнорира од PHP. Следните две цифри го означуваат типот на датотеката:

mode типови на датотеки
mode во октална форма Значење
0140000 socket
0120000 link
0100000 обична датотека
0060000 блоковен уред
0040000 directory
0020000 карактерен уред
0010000 fifo
Значи, на пример, една обична датотека може да биде 0100644 а директориум може да биде 0040755.

Во случај на грешка, stat() returns false.

Забелешка: Бидејќи типот на цел број на PHP е потпишан и многу платформи користат 32-битни цели броеви, некои функции за датотечниот систем може да вратат неочекувани резултати за датотеки поголеми од 2GB.

Errors/Exceptions

Бидејќи типот на податоци integer во PHP е со знакот и многу платформи користат 32-битни integers, некои функции за датотечниот систем може да вратат неочекувани резултати за датотеки поголеми од 2GB. E_WARNING се емитува.

Дневник на промени

Верзија = NULL
7.4.0 Додадена е опцијата create_process_group во параметрите options.
7.4.0 На size, atime, mtime and ctime При неуспех, еден NTS статистиките на симболичните врски се секогаш оние на целта. Претходно не беше случај за

Примери

Пример #1 stat() example

<?php
/* Get file stat */
$stat = stat('C:\php\php.exe');

/*
* Print file access time, this is the same
* as calling fileatime()
*/
echo 'Access time: ' . $stat['atime'];

/*
* Print file modification time, this is the
* same as calling filemtime()
*/
echo 'Modification time: ' . $stat['mtime'];

/* Print the device number */
echo 'Device number: ' . $stat['dev'];
?>

Пример #2 Користење stat() builds на Windows. touch()

<?php
/* Get file stat */
$stat = stat('C:\php\php.exe');

/* Did we failed to get stat information? */
if (!$stat) {
echo
'stat() call failed...';
} else {
/*
* We want the access time to be 1 week
* after the current access time.
*/
$atime = $stat['atime'] + 604800;

/* Touch the file */
if (!touch('some_file.txt', time(), $atime)) {
echo
'Failed to touch file...';
} else {
echo
'touch() returned success...';
}
}
?>

Белешки

Забелешка:

информации заедно со

Забелешка: Имајте предвид дека резолуцијата на времето може да се разликува од еден датотечен систем до друг. clearstatcache() за повеќе детали.

Совети

Резултатите од оваа функција се кеширани. Погледнете some Од PHP 5.0.0, оваа функција може да се користи и со Поддржани протоколи и обвивки URL обвивки. Погледнете stat() за да се утврди кои обвивки поддржуваат

Види Исто така

  • lstat() семејство на функционалност.
  • fstat() - Дава информации за датотека или симболична врска
  • filemtime() - Добива информации за датотека користејќи отворен покажувач на датотека
  • filegroup() - Добива време на модификација на датотеката
  • SplFileInfo

Белешки од корисници 18 белешки

webmaster na askapache dot com
пред 17 години
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. 

<?php

function alt_stat($file) {
 
 clearstatcache();
 $ss=@stat($file);
 if(!$ss) return false; //Couldnt stat file
 
 $ts=array(
  0140000=>'ssocket',
  0120000=>'llink',
  0100000=>'-file',
  0060000=>'bblock',
  0040000=>'ddir',
  0020000=>'cchar',
  0010000=>'pfifo'
 );
 
 $p=$ss['mode'];
 $t=decoct($ss['mode'] & 0170000); // File Encoding Bit
 
 $str =(array_key_exists(octdec($t),$ts))?$ts[octdec($t)]{0}:'u';
 $str.=(($p&0x0100)?'r':'-').(($p&0x0080)?'w':'-');
 $str.=(($p&0x0040)?(($p&0x0800)?'s':'x'):(($p&0x0800)?'S':'-'));
 $str.=(($p&0x0020)?'r':'-').(($p&0x0010)?'w':'-');
 $str.=(($p&0x0008)?(($p&0x0400)?'s':'x'):(($p&0x0400)?'S':'-'));
 $str.=(($p&0x0004)?'r':'-').(($p&0x0002)?'w':'-');
 $str.=(($p&0x0001)?(($p&0x0200)?'t':'x'):(($p&0x0200)?'T':'-'));
 
 $s=array(
 'perms'=>array(
  'umask'=>sprintf("%04o",@umask()),
  'human'=>$str,
  'octal1'=>sprintf("%o", ($ss['mode'] & 000777)),
  'octal2'=>sprintf("0%o", 0777 & $p),
  'decimal'=>sprintf("%04o", $p),
  'fileperms'=>@fileperms($file),
  'mode1'=>$p,
  'mode2'=>$ss['mode']),
 
 'owner'=>array(
  'fileowner'=>$ss['uid'],
  'filegroup'=>$ss['gid'],
  'owner'=>
  (function_exists('posix_getpwuid'))?
  @posix_getpwuid($ss['uid']):'',
  'group'=>
  (function_exists('posix_getgrgid'))?
  @posix_getgrgid($ss['gid']):''
  ),
 
 'file'=>array(
  'filename'=>$file,
  'realpath'=>(@realpath($file) != $file) ? @realpath($file) : '',
  'dirname'=>@dirname($file),
  'basename'=>@basename($file)
  ),

 'filetype'=>array(
  'type'=>substr($ts[octdec($t)],1),
  'type_octal'=>sprintf("%07o", octdec($t)),
  'is_file'=>@is_file($file),
  'is_dir'=>@is_dir($file),
  'is_link'=>@is_link($file),
  'is_readable'=> @is_readable($file),
  'is_writable'=> @is_writable($file)
  ),
  
 'device'=>array(
  'device'=>$ss['dev'], //Device
  'device_number'=>$ss['rdev'], //Device number, if device.
  'inode'=>$ss['ino'], //File serial number
  'link_count'=>$ss['nlink'], //link count
  'link_to'=>($s['type']=='link') ? @readlink($file) : ''
  ),
 
 'size'=>array(
  'size'=>$ss['size'], //Size of file, in bytes.
  'blocks'=>$ss['blocks'], //Number 512-byte blocks allocated
  'block_size'=> $ss['blksize'] //Optimal block size for I/O.
  ), 
 
 'time'=>array(
  'mtime'=>$ss['mtime'], //Time of last modification
  'atime'=>$ss['atime'], //Time of last access.
  'ctime'=>$ss['ctime'], //Time of last status change
  'accessed'=>@date('Y M D H:i:s',$ss['atime']),
  'modified'=>@date('Y M D H:i:s',$ss['mtime']),
  'created'=>@date('Y M D H:i:s',$ss['ctime'])
  ),
 );
 
 clearstatcache();
 return $s;
}

?>

|=---------[ 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
  )
)
webmaster na askapache dot com
12 години пред
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.

<?php

/**
 * Returns the number of running processes
 *
 * @link http://php.net/clearstatcache
 * @link http://php.net/stat  Description of stat syntax.
 * @author http://www.askapache.com/php/get-number-running-proccesses.html
 * @return int
 */
function get_process_count() {
  static $ver, $runs = 0;
  
  // check if php version supports clearstatcache params, but only check once
  if ( is_null( $ver ) )
    $ver = version_compare( PHP_VERSION, '5.3.0', '>=' );
 
  // Only call clearstatcache() if function called more than once */
  if ( $runs++ > 0 ) { // checks if $runs > 0, then increments $runs by one.
    
    // if php version is >= 5.3.0
    if ( $ver ) {
      clearstatcache( true, '/proc' );
    } else {
      // if php version is < 5.3.0
      clearstatcache();
    }
  }
  
  $stat = stat( '/proc' );
 
  // if stat succeeds and nlink value is present return it, otherwise return 0
  return ( ( false !== $stat && isset( $stat[3] ) ) ? $stat[3] : 0 );
}

?>

Example #1 get_process_count() example

<?php
$num_procs = get_process_count();
var_dump( $num_procs );
?>

The above example will output:

int(118)

Which is the number of processes that were running.
- Добива група на датотеката
20 години пред
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:

<?php
    if (date('I') == 1) $file_date -= 3600;
?>

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.
admin at smitelli dot com
пред 17 години
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:
<?php
    function getmodtime($file) { //returns the time a file was modified.
        $mtime = filemtime($file);
        //date('I') returns 1 if DST is on and 0 if off.
        $diff = date('I')-date('I', $mtime);
        //diff =  0 if file-time and os-time are both in the same DST setting
        //diff =  1 if os is DST and file is not
        //diff = -1 if file is DST and os is not
        return $mtime + $diff*3600;
    }
?>
Here's a test:
<?php
    //create two dummy files:
    $file0 = 'file1.txt';
    $file1 = 'file2.txt';
    file_put_contents($file0, '');
    file_put_contents($file1, '');
    
    $time0=strtotime('Jan 1 2008 10:00'); echo 'Date0 (ST): ' . date(DATE_COOKIE, $time0)."\n";
    $time1=strtotime('Aug 1 2008 10:00'); echo 'Date1 (DT): ' . date(DATE_COOKIE, $time1)."\n";
    touch($file0, $time0); //set file0 to Winter (Non-DST)
    touch($file1, $time1); //set file1 to Summer (DST)
    
    $ftime0 = filemtime($file0);
    $ftime1 = filemtime($file1);
    echo "\nUncorrected: \n";
    echo 'File 0: ' . ($ftime0-$time0) ."\n";
    echo 'File 1: ' . ($ftime1-$time1) ."\n";
    //if your system adjusts for DST, then _one_ of the above should be 3600 or -3600, depending on the time of year
    
    $ftime0 = getmodtime($file0); //use filemtime correction
    $ftime1 = getmodtime($file1); //use filemtime correction
    echo "\nCorrected: \n";
    echo 'File 0: ' . ($ftime0-$time0) ."\n";
    echo 'File 1: ' . ($ftime1-$time1) ."\n";
    //both of the corrected values output should be 0.
?>

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.
mail4rico at gmail dot com
20 години пред
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:

<?php
define('S_IFDIR',040000);
if ($mode & S_IFDIR)
{
  /*
    incorrect!
    format could be S_IFDIR, but also
    S_IFBLK, S_IFSOCK, or S_IFWHT.
  */
}
?>

...and should instead be:

<?php
define('S_IFMT',0170000);
define('S_IFDIR',040000);
if (S_IFDIR == ($mode & S_IFMT)) {  /* ... */  }
?>

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...
com dot gmail at algofoogle
ian at eiloart dot com
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.
salisbm на hotmail точка com
пред 22 години
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
JulieC
19 години пред
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.
marting.dc AT gmail.com
20 години пред
If you want to know a directory size, this function will help you:

<?php
function dir_size($dir)
{
    $handle = opendir($dir);
    
    while ($file = readdir($handle)) {
        if ($file != '..' && $file != '.' && !is_dir($dir.'/'.$file)) {
            $mas += filesize($dir.'/'.$file);
            } else if (is_dir($dir.'/'.$file) && $file != '..' && $file != '.') {
            $mas += dir_size($dir.'/'.$file);
        }
    }
    return $mas;
}
echo dir_size('DIRECTORIO').' Bytes';
?>
мао на nospam точка com
20 години пред
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:

<?php  

$conn = ssh2_connect($host, 22);
ssh2_auth_password($conn, $user, $password);
$stream = ssh2_exec($conn, "stat $fileName > $remotedest");
ssh2_scp_recv($conn, $remotedest, $localdest);
$farray = file($localdest);
print_r($farray);
?>
carlos [at] encore-lab [dot] com
пред 11 години
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.
digitalaudiorock на hotmail точка com
пред 17 години
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
svend на svendtofte точка com
21 години пред
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.
Ray.Paseur понекогаш користи Gmail
пред 5 години
A good explanation of the "mode" bits is given here:
https://www.php.net/manual/en/function.fileperms.php
Hellhound
пред 18 години
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);
Анонимен
19 години пред
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.

<?php

$mtime = filemtime($file);

if (date('I') == 1) {
    // Win DST is enabled, adjust standard time 
    // files back to 'real' file UTC.
    if (date('I', $mtime) == 0) {
        $mtime -= 3600;
    }
} else {
    // Win DST is disabled, adjust daylight time 
    // files forward to 'real' file UTC.
    if (date('I', $mtime) == 1) {
        $mtime += 3600;
    }
}

echo gmdate('Y-m-d H:i:s', $mtime);

?>

Just another example of why 'not' to use windows in a server room.
antonixyz на gmx точка net
пред 17 години
<?php
$stat = stat($filepath);
$mode = $stat[2];
?>
is identical to:
<?php $mode = fileperms($filepath); ?>

at least on my linux box.
Анонимен
21 години пред
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;
}
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.