- PHP функции filectime() fileatime() filemtime()
- Из документации
- Примеры
- Получим (без кэша):
- Получим (с кэшем):
- filemtime
- Parameters
- Return Values
- Errors/Exceptions
- Examples
- Notes
- See Also
- User Contributed Notes 30 notes
- PHP: how can I get file creation date?
- 4 Answers 4
- PHP: Как получить дату создания из загруженного файла?
- 5 ответов
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
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.
?php
$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: how can I get file creation date?
I am reading a folder with lots of files. How can I get the creation date of a file. I don’t see any direct function to get it. There are filemtime and filectime . And if the file hasn’t been modified, what will happen?
4 Answers 4
Use filectime. For Windows it will return the creation time, and for Unix the change time which is the best you can get because on Unix there is no creation time (in most filesystems).
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.
Returns the time the file was last changed, or FALSE on failure. The time is returned as a Unix timestamp.
@zod If you read a little further than the first lines you may understand more. Go into the comments a little too.
filemtime for Linux is better, more precise, as filectime is changed during owner, permission change asn other operations. You will get more chances to get creation time on Linux using filemtime
Would it be faster to run this php function or to pull a MySQL field for last updated? In my case image path is store in DB and already running a select query
This is the example code taken from the PHP documentation here: https://www.php.net/manual/en/function.filemtime.php
// outputs e.g. somefile.txt was last changed: December 29 2002 22:16:23. $filename = 'somefile.txt'; if (file_exists($filename))
The code specifies the filename, then checks if it exists and then displays the modification time using filemtime() .
filemtime() takes 1 parameter which is the path to the file, this can be relative or absolute.
While this code-only post might answer the question, please add an explanation of why it does so. This will help future readers evaluate the answer for their situation.
The code specifies the filename, then checks if it exists and then displays the modification time using filemtime(). filemtime() takes 1 parameter which is the path to the file, this can be relative or absolute.The example above is copied from the PHP documentation here php.net/manual/en/function.filemtime.php
Unfortunately if you are running on linux you cannot access the information as only the last modified date is stored.
It does slightly depend on your filesystem tho. I know that ext2 and ext3 do not support creation time but I think that ext4 does.
I know this topic is super old, but, in case if someone’s looking for an answer, as me, I’m posting my solution.
This solution works IF you don’t mind having some extra data at the beginning of your file.
Basically, the idea is to, if file is not existing, to create it and append current date at the first line. Next, you can read the first line with fgets(fopen($file, ‘r’)) , turn it into a DateTime object or anything (you can obviously use it raw, unless you saved it in a weird format) and voila — you have your creation date! For example my script to refresh my log file every 30 days looks like this:
if (file_exists($logfile)) < $now = new DateTime(); $date_created = fgets(fopen($logfile, 'r')); if ($date_created == '') < file_put_contents($logfile, date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND | LOCK_EX); >$date_created = new DateTime($date_created); $expiry = $date_created->modify('+ 30 days'); if ($now >= $expiry) < unlink($logfile); >>
PHP: Как получить дату создания из загруженного файла?
Проблема: Я хочу определить исходное время создания файла из файла, загруженного на мой сервер через PHP. Я понимаю, что файл копируется из клиента во временный файл на моем сервере, который затем ссылается на $_FILES var. Временный файл, конечно, бесполезен, потому что он только что был создан. Есть ли способ получить дату создания из исходного файла клиентов? Спасибо
5 ответов
Эти данные не отправляются браузером, поэтому нет доступа к нему. Данные, отправленные вместе с файлом, это mime-type , filename и содержимое файла.
Если вам нужна дата создания, вам потребуется либо предоставить ее пользователю, либо создать специальный механизм загрузки файлов через Flash или Java.
Спасибо всем! С другой стороны: это обычная практика — указывать дату создания внутри содержимого файла? Это файл .w3g (файл воспроизведения, связанный с Warcraft 3). Если есть вероятность, что создатель файла поместит дату создания в файл, я выделю некоторое время для дальнейшего ее изучения. Просто интересно, есть ли какой-нибудь способ «обычной практики», чтобы дать мне подсказку о том, есть ли дата там или нет.
Нет, поток данных записывается в файл в каталоге tmp вместо файла, который просто «скопирован» на ваш веб-сервер, и это технически «новый» файл.
Я не понимаю разницу между потоковой передачей и копированием. Разве вы не в обоих случаях просто переносили байты из одного места в другое? Или есть разница в метаданных, которые передаются?
Ну, это было больше, чтобы помочь вам «увидеть» процесс, чтобы иметь смысл. Дело в том, что созданные / измененные данные сохраняются в файловой системе, а не в самом содержимом файла. Поэтому, когда браузер отправляет файл, он просто отправляет фактическое содержимое файла и никакой дополнительной информации. Flash — действительно лучший вариант, если вам это нужно, поскольку класс FileReference предоставляет вам (на стороне клиента) доступ к тем данным, которые вы могли бы отправить вручную при загрузке.