PHP: filectime - Manual (2024)

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

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

Описание

filectime(string $filename): int|false

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

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

filename

Путь к файлу.

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

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

Ошибки

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

Примеры

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

<?php// Пример вывода: Файл 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));
}
?>

Примечания

Замечание:

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

Замечание:

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

Замечание:

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

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

Подсказка

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

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

  • filemtime() - Получает время последнего изменения файла

+add a note

User Contributed Notes 9 notes

up

down

15

StevieMc at example dot com

17 years ago

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

<?PHP
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);$i = 0;//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. <br/>"";
}

}
?>

I hope this is useful to somebody.

up

down

3

faketruth at yandex dot ru

9 years ago

If you need file creation time on Mac OS X:

<?php
if ($handle = popen('stat -f %B ' . escapeshellarg($filename), 'r')) {
$btime = trim(fread($handle, 100));
echo
strftime("btime: %Y.%m.%d %H:%M:%S\n", $btime);
pclose($handle);
}
?>

up

down

3

javi at live dot com

15 years ago

Filemtime seems to return the date of the EARLIEST modified file inside a folder, so this is a recursive function to return the date of the LAST (most recently) modified file inside a folder.

<?php// Only take into account those files whose extensions you want to show.
$allowedExtensions = array(
'zip',
'rar',
'pdf',
'txt'
);

function

filemtime_r($path)
{
global
$allowedExtensions;

if (!

file_exists($path))
return
0;$extension = end(explode(".", $path));
if (
is_file($path) && in_array($extension, $allowedExtensions))
return
filemtime($path);
$ret = 0;

foreach (

glob($path."/*") as $fn)
{
if (
filemtime_r($fn) > $ret)
$ret = filemtime_r($fn);
// This will return a timestamp, you will have to use date().
}
return
$ret;
}
?>

up

down

2

coolkoon at gmail dot com

13 years ago

You should avoid feeding the function files without a path. This applies for filemtime() and possibly fileatime() as well. If you omit the path the command will fail with the warning "filectime(): stat failed for filename.php".

up

down

1

website at us dot kaspersky dot com

16 years ago

Line 37 of the code above has an error.

echo "File name: $file - Date Added: $date. <br/>"";

There is an extra " after the <br/> that needs to be deleted in order for this code to work.

up

down

1

m dot rabe at directbox dot com

14 years ago

Under Windows you can use fileatime() instead of filectime().

up

down

1

chuck dot reeves at gmail dot com

16 years ago

filectime running on windows reading a file from a samba share, will still show the last modified date.

up

down

soapergem at gmail dot com

14 years ago

Note that on Windows systems, filectime will show the file creation time, as there is no such thing as "change time" in Windows.

up

down

-1

laurent dot pireyn at wanadoo dot be

22 years ago

If you use filectime with a symbolic link, you will get the change time of the file actually linked to. To get informations about the link self, use lstat.

+add a note

PHP: filectime - Manual (2024)

References

Top Articles
Latest Posts
Article information

Author: Dong Thiel

Last Updated:

Views: 5600

Rating: 4.9 / 5 (59 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Dong Thiel

Birthday: 2001-07-14

Address: 2865 Kasha Unions, West Corrinne, AK 05708-1071

Phone: +3512198379449

Job: Design Planner

Hobby: Graffiti, Foreign language learning, Gambling, Metalworking, Rowing, Sculling, Sewing

Introduction: My name is Dong Thiel, I am a brainy, happy, tasty, lively, splendid, talented, cooperative person who loves writing and wants to share my knowledge and understanding with you.