file modification time php

PHP: Get the last modification time of a file.

This is a tutorial on how to get the last modification time of a file using PHP. To get the time and date that a file was created or last modified, we can use PHP’s filemtime function. This function will return the modification time in a Unix format.

Take a look at the following PHP example:

In the code above, we:

When I ran the PHP snippet above, the result was as follows:

log.txt was last modified on 09 Jan 2020 11:43:19

The modification time for my file is 01 Jan 1970?!

If filemtime is unable to find the last modification time, it will return a FALSE value. If a FALSE value gets passed into PHP’s date function, the end result will be similar to 01 Jan 1970 01:00:00. This is because false will be treated as 0 and 0 in Unix is the 1st of January, 1970.

OK, so why is filemtime returning FALSE?

If filemtime is returning FALSE, then you need to check the following:

The modification time on my file isn’t updating?

The results of filemtime are automatically cached by PHP for performance reasons. In order to force filemtime to return the latest modification time, you will have to call the clearstatcache function like so:

This can be especially important for PHP scripts that read the last modification time of a particular file multiple times.

Источник

PHP file modification time in milliseconds

I there, I am currently writing a unit test which asserts that a file did not get modified. The test code execution takes less than one second and therefore I would like to know if it is possible to retrieve the file modification time in milliseconds. filemtime() function returns the UNIX timestamp in seconds.

My current solution is using the sleep(1) function which will assure me that 1 second passed before checking if it was modified or not. I don’t like that solution since it slows down the test by a great deal.

I cannot assert the content equality via get_file_contents() since the data that can be rewritten would be the same.

I am guessing it is impossible, is it?

file modification time php. Смотреть фото file modification time php. Смотреть картинку file modification time php. Картинка про file modification time php. Фото file modification time php

5 Answers 5

file modification time php. Смотреть фото file modification time php. Смотреть картинку file modification time php. Картинка про file modification time php. Фото file modification time php

Try this simple command:

and you can see the file timestamp precision is not second, it is more precise. (using Linux, but don’t think it differs in Unix) but I still don’t know of a PHP function for getting precise timestamp, maybe you can parse the result of the system call.

file modification time php. Смотреть фото file modification time php. Смотреть картинку file modification time php. Картинка про file modification time php. Фото file modification time php

AFAIK UNIX timestamp’s precision is seconds, so this may not be a possibility.

BTW, note that PHP caches the return value of filemtime() internally, thus clearstatcache() should be called before.

An alternative method could be to modify (or delete) the contents of the file first so that you can easily identify changes. Since the state of the system should remain the same after each test is executed, it would make sense anyways to restore the original file contents after the unit test has run.

If the file system is ext4 (common on more recent unixes / linuxes like Ubuntu) or ntfs (Windows), then the mtime does have sub-second precision.

If the file system is ext3 (or perhaps others; this was the standard a while ago and is still used by RHEL), then the mtime is only stored to the nearest second. Perhaps that old default is why PHP only supports mtime to the nearest second.

To fetch the value in PHP, you need to call an external util, since PHP itself does not support it.

Hmm. Imagine a web server where we use a combination of PHP and say for example nodeJS. In nodeJS land when we get the modification time of a file it includes the milliseconds. In PHP it does not. Now lets say that for any large files (many Gigabytes) which we allow the user to download we have and maintain corresponding file containing the pre-calculated MD5 checksum of the entire file. We store this checksum in a file with the same name as the original file but prepended also with the size and modification time of the file. INCLUDING THE MILLISECONDS! (with all of that being done by node)

Example: GEBCO_2019.nc (11723617646 bytes) and GEBCO_2019.nc.11723617646-2019-10-31T15-03-06.687Z.md5

Now on the downloads page we decide to display the MD5 checksum This is using PHP code

We call filemtime but alas we can’t get the milliseconds so we can’t work out the name of the Md5 file.

WE COULD CHANGE THE NODE CODE to ignore the millisecond part.

Its like the deficiency in PHP here is causing us to choose a lower common denominator than we should have to.

It’s also exceptionally HORRIBLE to have to resort to running an external program just to get the file modification time. If you had to do this 50 or 60 times for a single page load I expect it would slow things down just a bit.

Now the accuracy of file mod time is of course system dependent. PHP should directly provide us with a way to get this time and it’s a serious deficiency if it cannot.

Источник

filemtime

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

filemtime — Gets file modification time

Description

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.

Notes

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

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.

Cheaper and dirtier way to code a cache:

= ‘URI to cache file’ ;
$cache_life = ‘120’ ; //caching time, in seconds

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:

else
$adjustment = 0 ;

A comment below states

«When using this function to get the modified date of a directory,
it returns the date of the file in that directory that was last modified.»

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).

If PHP’s integer type is only 32 bits on your system, filemtime() will fail on files over 2GB with the warning «stat failed». All stat()-related commands will exhibit the same behavior.

As a workaround, you can call the system’s stat command to get the modification time of a file:

Thanks to «mpb dot mail at gmail dot com» for his/her similar comment on stat().

While testing on Windows, I noticed that the precision of filemtime is just 1 second.

So if you use clearstatcache() and filemtime() to check if a file has been modified, it might fail to detect the change. The modifications just have to happen within less than a second.

(I ran into this with Apache on Windows XP.)

Here is a handy script to create a csv file with file names and the date when files in a given folder were inserted:

( «Pragma: public» );
header ( «Cache-Control: private» );
header ( «Content-Type: text/csv» );
header ( «Content-Disposition: attachment; filename=age-of-files.csv» );

i needed the ability to grab the mod time of an image on a remote site. the following is the solution with the help of Joe Ferris.

To find the oldest file in a directory :
$directory= «C:\\»;

if ($handle = opendir($directory)) <

It could be useful to determinate the timestamp of the newest file in a directory. (e.g. if you want to find out when the last change was made to your project).

Following function will help you:

concerning «notepad at codewalkers dot com»‘s code:

this code is pretty neat, but i just wanted to note that using the «HEAD»-method instead of the «GET»-method in the http-request might be preferrable, since then not the whole resource is being downloaded.

http/1.1 definiton snippet:
Section «9.4 HEAD»

the code would then be.

Also on 32-bit systems, filemtime() also does not work for files with modification time set beyond Jan 2038. It is the dreaded time_t overflow bug for unix seconds.

On windows you can set the system time to any arbitrary future date, and any new files you created or edited will automatically change to that future date.

If exec isn’t permitted for some reason, and if you could access the file via an web url (e.g. http://localhost/yourfile.txt), another workaround is to get the Last-Modified time from the HTTP headers (e.g. get_headers(url) ), and parse it as a DateTime object.

I have tested it and it works for years like 2050 and 3012.

Cheap and dirty way to code a cache:

= ‘URI to cache file’ ;
$cache_life = ‘120’ ; //caching time, in seconds

Here is a small but handy script that you can use to find which files in your server are modified after a date/time that you specify. This script will go through all folders in the specified directory recursively and echo the modified files with the last modified date/time.

//Starts Here
//Put here the directory you want to search for. Put / if you want to search your entire domain
$dir=’/’;

//Put the date you want to compare with in the format of: YYYY-mm-dd hh:mm:ss
$comparedatestr=»2006-08-12 00:00:00″;
$comparedate=strtotime($comparedatestr);

//I run the function here to start the search.
directory_tree($dir,$comparedate);

//This is the function which is doing the search.
function directory_tree($address,$comparedate)<

if($comparedate ‘.$last_modified_str;
echo «
«;
>

Please note that many of the functions below that people have provided to get files modified after a certain time in a directory will NOT get all files on a Windows operating system.

If you copy and paste any file inside the folder or into the folder from another folder (such as images that may be used but aren’t going to be modified right away), the modified time is not updated on these copied files, only the creation time.

You need to use filectime with filemtime to assure you get copied files that aren’t modified but are obviously new.

when working with swf files (flash animations), there is a nice way to avoid the browser cache. i used to do this by hand, then i used a random number, but with large animations while working online, it gets boring because the server always downloads the whole animation, even if there was no change.
but.

this will do the trick

The mentioned example:

works, however is not ideal from a performance point of view of serving static files through PHP, since it basically needs two perform two file system operations (file_exists and filemtime). A more effective way would be to only use filemtime and save the overhead of file_exists using:

filemtime(..) only works with files on your server.
$T=filesize(«index.php»); // Works.
$T=filesize(«/public_html/dir/index.php»); // Works.

But the following will not work.
$T=filesize(«https://mydomain.com/dir/index.php»); // Will not work. Same domain but using web address.
$T=filesize(«https://otherdomain.com/dir/index.php»); // Other domain, will not work.

To get file date for other sites try:
(Note: Time zone may be in G.M.T. and not your local timezone)

$ret = curl_getinfo($ch, CURLINFO_FILETIME);
curl_close($ch);

The second script above will ensure any updated image is guaranteed to replace its predecessor without forcing the browser to reload the image on every visit.

A little amendment to «tobias» post:

filemtime() returns false on failure so in the first example it will never display the date modified.

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.

Источник

filemtime

filemtime — Возвращает время последнего изменения файла

Описание

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

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

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

Примеры

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

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

Ошибки

Примечания

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

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

Коментарии

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

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.

Regards,
Frank Keijzers

A comment below states

«When using this function to get the modified date of a directory,
it returns the date of the file in that directory that was last modified.»

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, 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.

i needed the ability to grab the mod time of an image on a remote site. the following is the solution with the help of Joe Ferris.

concerning «notepad at codewalkers dot com»‘s code:

this code is pretty neat, but i just wanted to note that using the «HEAD»-method instead of the «GET»-method in the http-request might be preferrable, since then not the whole resource is being downloaded.

http/1.1 definiton snippet:
Section «9.4 HEAD»

the code would then be.

If PHP’s integer type is only 32 bits on your system, filemtime() will fail on files over 2GB with the warning «stat failed». All stat()-related commands will exhibit the same behavior.

As a workaround, you can call the system’s stat command to get the modification time of a file:

Thanks to «mpb dot mail at gmail dot com» for his/her similar comment on stat().

Here is a small but handy script that you can use to find which files in your server are modified after a date/time that you specify. This script will go through all folders in the specified directory recursively and echo the modified files with the last modified date/time.

//Starts Here
//Put here the directory you want to search for. Put / if you want to search your entire domain
$dir=’/’;

//Put the date you want to compare with in the format of: YYYY-mm-dd hh:mm:ss
$comparedatestr=»2006-08-12 00:00:00″;
$comparedate=strtotime($comparedatestr);

//I run the function here to start the search.
directory_tree($dir,$comparedate);

//This is the function which is doing the search.
function directory_tree($address,$comparedate)<

if($comparedate ‘.$last_modified_str;
echo «
«;
>

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.

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.

It could be useful to determinate the timestamp of the newest file in a directory. (e.g. if you want to find out when the last change was made to your project).

Following function will help you:

Please note that many of the functions below that people have provided to get files modified after a certain time in a directory will NOT get all files on a Windows operating system.

If you copy and paste any file inside the folder or into the folder from another folder (such as images that may be used but aren’t going to be modified right away), the modified time is not updated on these copied files, only the creation time.

You need to use filectime with filemtime to assure you get copied files that aren’t modified but are obviously new.

when working with swf files (flash animations), there is a nice way to avoid the browser cache. i used to do this by hand, then i used a random number, but with large animations while working online, it gets boring because the server always downloads the whole animation, even if there was no change.
but.

Источник

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.

And if the file hasn’t been modified, what will happen?

file modification time php. Смотреть фото file modification time php. Смотреть картинку file modification time php. Картинка про file modification time php. Фото file modification time php

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.

file modification time php. Смотреть фото file modification time php. Смотреть картинку file modification time php. Картинка про file modification time php. Фото file modification time php

This is the example code taken from the PHP documentation here: https://www.php.net/manual/en/function.filemtime.php

filemtime() takes 1 parameter which is the path to the file, this can be relative or absolute.

file modification time php. Смотреть фото file modification time php. Смотреть картинку file modification time php. Картинка про file modification time php. Фото file modification time 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.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *