Получение даты создания файла php

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

Источник

Читайте также:  Пропустить только буквы php

filectime

Returns the time the file was last changed, or false on failure. The time is returned as a Unix timestamp.

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Examples

Example #1 A filectime() example

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

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

Notes

Note:

Note: In most Unix filesystems, a file is considered changed when its inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated. See also filemtime() (which is what you want to use when you want to create «Last Modified» footers on web pages) and fileatime() .

Note:

Note also that in some Unix texts the ctime of a file is referred to as being the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems.

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

User Contributed Notes 9 notes

This method gets all the files in a directory, and echoes them in the order of the date they were added (by ftp or whatever).

function dirList ( $directory , $sortOrder )

//Get each file and add its details to two arrays
$results = array();
$handler = opendir ( $directory );
while ( $file = readdir ( $handler )) <
if ( $file != ‘.’ && $file != ‘..’ && $file != «robots.txt» && $file != «.htaccess» ) $currentModified = filectime ( $directory . «/» . $file );
$file_names [] = $file ;
$file_dates [] = $currentModified ;
>
>
closedir ( $handler );

//Sort the date array by preferred order
if ( $sortOrder == «newestFirst» ) arsort ( $file_dates );
>else asort ( $file_dates );
>

//Match file_names array to file_dates array
$file_names_Array = array_keys ( $file_dates );
foreach ( $file_names_Array as $idx => $name ) $name = $file_names [ $name ];
$file_dates = array_merge ( $file_dates );

//Loop through dates array and then echo the list
foreach ( $file_dates as $file_dates ) $date = $file_dates ;
$j = $file_names_Array [ $i ];
$file = $file_names [ $j ];
$i ++;

echo «File name: $file — Date Added: $date .
«»;
>

I hope this is useful to somebody.

Источник

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.

Читайте также:  Github java example code

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.

Читайте также:  Last element foreach javascript

// 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

Источник

filectime

Возвращает время изменения индексного дескриптора (inode) файла.

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

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

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

Примеры

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

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

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

Ошибки

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

Примечания

Замечание:

Примечание. На большинстве платформ Unix, файл считается измененным, если изменены данные его индексного дескриптора, что включает информацию о правах на файл, о его владельце, группе и другие метаданные, содержащиеся в индексном дескрипторе. Обратитесь также к описаниям функций filemtime() (данная функция полезна для создания сообщений типа: «Последнее обновление от. » на web-страницах) и fileatime() .

Замечание:

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

Замечание:

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

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

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

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

Источник

Оцените статью