Php получить дату изменения файла

fileatime

Возвращает время, когда в последний раз был осуществлён доступ к указанному файлу или false в случае возникновения ошибки. Время возвращается в виде временной метки Unix.

Ошибки

В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .

Примеры

Пример #1 Пример использования функции fileatime()

// Пример вывода: В последний раз обращение к файлу somefile.txt было произведено: December 29 2002 22:16:23.

$filename = ‘somefile.txt’ ;
if ( file_exists ( $filename )) echo «В последний раз обращение к файлу $filename было произведено: » . date ( «F d Y H:i:s.» , fileatime ( $filename ));
>

Примечания

Замечание:

Предполагается, что время последнего доступа файла изменяется во время чтения блоков файла. Это может потребовать значительного количества системных ресурсов, особенно когда приложение обращается к большому числу файлов или каталогов.

С целью увеличения производительности некоторые файловые системы на платформах Unix могут быть примонтированы с отключённой возможностью обновления времени последнего доступа к файлам, примером этого могут служить каталоги для хранения сообщений USENET. В подобных случаях использование данной функции бессмысленно.

Замечание:

Учтите, что обработка времени может отличаться в различных файловых системах.

Замечание: Результаты этой функции кешируются. Более подробную информацию смотрите в разделе clearstatcache() .

Начиная с PHP 5.0.0, эта функция также может быть использована с некоторыми обёртками url. Список обёрток, поддерживаемых семейством функций stat() , смотрите в разделе Поддерживаемые протоколы и обёртки.

Смотрите также

  • filemtime() — Возвращает время последнего изменения файла
  • fileinode() — Возвращает индексный дескриптор файла
  • date() — Форматирует временную метку Unix

Источник

filemtime

Данная функция возвращает время последней записи блоков файла, иначе говоря, изменения содержания файла.

Список параметров

Возвращаемые значения

Возвращает время последнего изменения указанного файла, или FALSE в случае возникновения ошибки. Время возвращается в формате временной метки Unix, который подходит для передачи в качестве аргумента функции date() .

Примеры

Пример #1 Пример использования функции filemtime()

// Пример вывода: В последний раз файл somefile.txt был изменен: December 29 2002 22:16:23.

$filename = ‘somefile.txt’ ;
if ( file_exists ( $filename )) echo «В последний раз файл $filename был изменен: » . date ( «F d Y H:i:s.» , filemtime ( $filename ));
>
?>

Ошибки

В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .

Примечания

Замечание:

Учтите, что обработка времени может отличаться в различных файловых системах.

Замечание: Результаты этой функции кэшируются. Более подробную информацию смотрите в разделе clearstatcache() .

Начиная с PHP 5.0.0, эта функция также может быть использована с некоторыми обертками url. Список оберток, поддерживаемых семейством функций stat() , смотрите в Поддерживаемые протоколы и обработчики (wrappers).

Смотрите также

  • filectime() — Возвращает время изменения индексного дескриптора файла
  • stat() — Возвращает информацию о файле
  • touch() — Устанавливает время доступа и модификации файла
  • getlastmod() — Определение времени последней модификации страницы

Источник

filemtime

This function returns the time when the data blocks of a file were being written to, that is, the time when the content of the file was changed.

Parameters

Return Values

Returns the time the file was last modified, or false on failure. The time is returned as a Unix timestamp, which is suitable for the date() function.

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Examples

Example #1 filemtime() example

// outputs e.g. somefile.txt was last modified: December 29 2002 22:16:23.

$filename = ‘somefile.txt’ ;
if ( file_exists ( $filename )) echo » $filename was last modified: » . date ( «F d Y H:i:s.» , filemtime ( $filename ));
>
?>

Notes

Note:

Note that time resolution may differ from one file system to another.

Note: The results of this function are cached. See clearstatcache() for more details.

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • filectime() — Gets inode change time of file
  • stat() — Gives information about a file
  • touch() — Sets access and modification time of file
  • getlastmod() — Gets time of last page modification

User Contributed Notes 30 notes

This is a very handy function for dealing with browser caching. For example, say you have a stylesheet and you want to make sure everyone has the most recent version. You could rename it every time you edit it, but that would be a pain in the ass. Instead, you can do this:

By appending a GET value (the UNIX timestamp) to the stylesheet URL, you make the browser think the stylesheet is dynamic, so it’ll reload the stylesheet every time the modification date changes.

To get the last modification time of a directory, you can use this:


$getLastModDir = filemtime("/path/to/directory/.");

Take note on the last dot which is needed to see the directory as a file and to actually get a last modification date of it.

This comes in handy when you want just one ‘last updated’ message on the frontpage of your website and still taking all files of your website into account.

«this is not (necessarily) correct, the modification time of a directory will be the time of the last file *creation* in a directory (and not in it’s sub directories).»

This is not (necessarily) correct either. In *nix the timestamp can be independently set. For example the command «touch directory» updates the timestamp of a directory without file creation.

Also file removal will update the timestamp of a directory.

To get the modification date of some remote file, you can use the fine function by notepad at codewalker dot com (with improvements by dma05 at web dot de and madsen at lillesvin dot net).

But you can achieve the same result more easily now with stream_get_meta_data (PHP>4.3.0).

However a problem may arise if some redirection occurs. In such a case, the server HTTP response contains no Last-Modified header, but there is a Location header indicating where to find the file. The function below takes care of any redirections, even multiple redirections, so that you reach the real file of which you want the last modification date.

// get remote file last modification date (returns unix timestamp)
function GetRemoteLastModified ( $uri )
// default
$unixtime = 0 ;

$fp = fopen ( $uri , «r» );
if( ! $fp )

$MetaData = stream_get_meta_data ( $fp );

foreach( $MetaData [ ‘wrapper_data’ ] as $response )
// case: redirection
if( substr ( strtolower ( $response ), 0 , 10 ) == ‘location: ‘ )
$newUri = substr ( $response , 10 );
fclose ( $fp );
return GetRemoteLastModified ( $newUri );
>
// case: last-modified
elseif( substr ( strtolower ( $response ), 0 , 15 ) == ‘last-modified: ‘ )
$unixtime = strtotime ( substr ( $response , 15 ) );
break;
>
>
fclose ( $fp );
return $unixtime ;
>
?>

There’s a deeply-seated problem with filemtime() under Windows due to the fact that it calls Windows’ stat() function, which implements DST (according to this bug: http://bugs.php.net/bug.php?id=40568). The detection of DST on the time of the file is confused by whether the CURRENT time of the current system is currently under DST.

This is a fix for the mother of all annoying bugs:

function GetCorrectMTime ( $filePath )

$time = filemtime ( $filePath );

$isDST = ( date ( ‘I’ , $time ) == 1 );
$systemDST = ( date ( ‘I’ ) == 1 );

return ( $time + $adjustment );
>
?>

Dustin Oprea

Источник

PHP функции filectime() fileatime() filemtime()

Функции PHP filectime() fileatime() filemtime() очень похожи друг на друга. Легко запутаться, когда и какой нужно использовать — какая функция, какую метку времени получает. В этой заметке разберем что тут к чему — какие метки времени сохраняются при создании файла, какие при изменении или чтении файлов.

Из документации

filectime( $file_path ) (create) Возвращает время последнего изменения указанного файла. Изменяется при создании, изменении файла. Эта функция проверяет наличие изменений в Inode файла, и обычных изменений. Изменения Inode — это изменение разрешений, владельца, группы и других метаданных. filemtime( $file_path ) (modified) Возвращает время последнего изменения контента файла. Изменяется при изменении контента файла. fileatime( $file_path ) (access) Возвращает время последнего доступа к файлу. Изменяется при чтении файла (не всегда). Заметка: на большинстве серверах такие обновления времени доступа к файлу отключены, так как эта функция снижает производительность приложений, регулярно обращающихся к файлам.

Возвращают

Все функции кэшируют результат. Чтобы сбросить кэш используйте функцию clearstatcache() . Пример кэша. Если в одном PHP процессе сначала использовать одну из «функции», а затем изменить данные или контент файла (использовать touch() , file_put_contents() ) и попробовать снова использовать «функции», то функции вернут первый результат, хотя на самом деле он изменился.

Примеры

$file = FC_PARSER_PATH . 'info/_temp_test_file'; @ unlink( $file ); file_put_contents( $file, 'content' ); $__echo = function() use ($file)< clearstatcache(); // очищаем кэш echo time() ."\t time()\n"; echo filectime( $file ) ."\t filectime()\n"; echo filemtime( $file ) ."\t filemtime()\n"; echo fileatime( $file ) ."\t fileatime()\n"; >; $__echo(); sleep(1); echo "\n\nchmod()\n"; chmod( $file, 0777 ); $__echo(); sleep(1); echo "\n\nfile_get_contents()\n"; file_get_contents( $file ); $__echo(); sleep(1); echo "\n\nfile_put_contents()\n"; file_put_contents( $file, 'content2' ); $__echo(); echo "\n\ntouch()\n"; touch( $file, 22222222222, 33333333333 ); touch( $file, 44444444444, 55555555555 ); $__echo();

Получим (без кэша):

1540437788 time() 1540437788 filectime() 1540437788 filemtime() 1540437788 fileatime() chmod() 1540437789 time() 1540437789 filectime() 1540437788 filemtime() 1540437788 fileatime() file_get_contents() 1540437790 time() 1540437789 filectime() 1540437788 filemtime() 1540437788 fileatime() file_put_contents() 1540437791 time() 1540437791 filectime() 1540437791 filemtime() 1540437788 fileatime() touch() 1540437791 time() 1540437791 filectime() 44444444444 filemtime() 55555555555 fileatime()

По результату можно сказать:

Функция Меняет Не меняет
chmod() ctime mtime , atime
file_put_contents() ctime и mtime atime
touch() ctime , mtime , atime
file_get_contents() может менять atime ctime , mtime

file_get_contents() ничего не меняет в этом примере, потому что изменение atime почти всегда отключено на сервере для производительности.

Получим (с кэшем):

1540437873 time() 1540437873 filectime() 1540437873 filemtime() 1540437873 fileatime() chmod() 1540437874 time() 1540437873 filectime() 1540437873 filemtime() 1540437873 fileatime() file_get_contents() 1540437875 time() 1540437873 filectime() 1540437873 filemtime() 1540437873 fileatime() file_put_contents() 1540437876 time() 1540437873 filectime() 1540437873 filemtime() 1540437873 fileatime() touch() 1540437876 time() 1540437873 filectime() 1540437873 filemtime() 1540437873 fileatime()
До этого из: PHP

Источник

Читайте также:  Переменные среды python pycharm
Оцените статью