In php I can change the file last modification and access time arbitrarily with touch()
<?php
touch($filename,mktime(0,0,0,2010,1,10));
…but how to change the creation time?
Why do I need this? Well, If I retrodate a file or a directory mtime to before their creation date, explorer.exe keeps showing me the more recent creation date instead.
asked Jun 21, 2012 at 23:28
ZJRZJR
9,1254 gold badges30 silver badges37 bronze badges
2
Mh, an unsatisfactory, but working, approach I found out about, is: using nircmd.
Nircmd is a 37kb utility. (redistributable, closed-source, freeware)
How to proceed:
<?php
$time=strftime('%d-%m-%Y %H:%M:%S',$time);
$cmd=".\nircmdc.exe setfilefoldertime "$filename" "$time"";
system($cmd);
Notes:
- nircmdc.exe is the command line version of nircmd (note the additional
cbefore.exe) - setfilefoldertime is a nircmd sub-command, it is documented here.
Still, I hope there is a COM or WMIC solution I couldn’t find this time around.
answered Jun 22, 2012 at 1:56
ZJRZJR
9,1254 gold badges30 silver badges37 bronze badges
2
Try this one you can change file creation time and modify time
Win32 Console ToolBox 1.1
exec('touch.exe /c /t "file.html" '. date('H:i:s'));
nircmdc -> is to powerful
answered Dec 30, 2016 at 22:46
user956584user956584
5,1902 gold badges39 silver badges50 bronze badges
In php I can change the file last modification and access time arbitrarily with touch()
<?php
touch($filename,mktime(0,0,0,2010,1,10));
…but how to change the creation time?
Why do I need this? Well, If I retrodate a file or a directory mtime to before their creation date, explorer.exe keeps showing me the more recent creation date instead.
asked Jun 21, 2012 at 23:28
ZJRZJR
9,1254 gold badges30 silver badges37 bronze badges
2
Mh, an unsatisfactory, but working, approach I found out about, is: using nircmd.
Nircmd is a 37kb utility. (redistributable, closed-source, freeware)
How to proceed:
<?php
$time=strftime('%d-%m-%Y %H:%M:%S',$time);
$cmd=".\nircmdc.exe setfilefoldertime "$filename" "$time"";
system($cmd);
Notes:
- nircmdc.exe is the command line version of nircmd (note the additional
cbefore.exe) - setfilefoldertime is a nircmd sub-command, it is documented here.
Still, I hope there is a COM or WMIC solution I couldn’t find this time around.
answered Jun 22, 2012 at 1:56
ZJRZJR
9,1254 gold badges30 silver badges37 bronze badges
2
Try this one you can change file creation time and modify time
Win32 Console ToolBox 1.1
exec('touch.exe /c /t "file.html" '. date('H:i:s'));
nircmdc -> is to powerful
answered Dec 30, 2016 at 22:46
user956584user956584
5,1902 gold badges39 silver badges50 bronze badges
(PHP 4, PHP 5, PHP 7, PHP 
filectime — Gets inode change time of file
Description
filectime(string $filename): int|false
Parameters
-
filename -
Path to the file.
Return Values
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
<?php// 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.
StevieMc at example dot com ¶
16 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.
website at us dot kaspersky dot com ¶
15 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.
m dot rabe at directbox dot com ¶
13 years ago
Under Windows you can use fileatime() instead of filectime().
faketruth at yandex dot ru ¶
7 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:%Sn", $btime);
pclose($handle);
}
?>
soapergem at gmail dot com ¶
13 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.
javi at live dot com ¶
14 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;
}?>
coolkoon at gmail dot com ¶
12 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".
chuck dot reeves at gmail dot com ¶
15 years ago
filectime running on windows reading a file from a samba share, will still show the last modified date.
laurent dot pireyn at wanadoo dot be ¶
21 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.
- Главная
- Блог
- Поиск
- Контакты
Подробный поиск
|
Android |
Apache |
Bitrix CMS |
Centos |
|
Class |
CSS |
Debian |
Delphi |
|
Docker |
Drupal |
git |
HTML |
|
JavaScript |
Joomla |
JQuery |
JQuery UI |
|
Laravel |
Linux |
MODx |
MTG |
|
openCart |
PHP |
Python |
raspberry pi 3 / arduino |
|
regexp |
Script / Tool |
Smarty |
Soft |
|
SQL |
WebAsyst (shop-script) |
WordPress |
Алгоритмы |
|
Безопасность |
Игры |
Книги |
Настройка / Конфиги |
|
Сторонние сервисы |
Управление проектами |
Фильмы |
20.09.2012
Конвертируем дату для использования в touch
1 |
$date1 = '2010-09-09 18:06:22'; touch ('my.file', strtotime($date1)); |
Категории: PHP
Функции PHP filectime() fileatime() filemtime() очень похожи друг на друга и, когда ими нужно воспользоваться, легко запутаться, какая функция, какую метку времени получает. В этой заметке попробуем разобраться, какие метки времени сохраняются при создании, изменении или чтении файлов.
Из документации
- filectime( $file_path ) (create)
-
Возвращает время последнего изменения указанного файла. Изменяется при создании, изменении файла.
Эта функция проверяет наличие изменений в Inode файла, и обычных изменений. Изменения Inode — это изменение разрешений, владельца, группы и других метаданных.
- filemtime( $file_path ) (modified)
- Возвращает время последнего изменения контента файла. Изменяется при изменении контента файла.
- fileatime( $file_path ) (access)
-
Возвращает время последнего доступа к файлу. Изменяется при чтении файла (не всегда).
Заметка: на большинстве серверах такие обновления времени доступа к файлу отключены, так как эта функция снижает производительность приложений, регулярно обращающихся к файлам.
Возвращают
Число/false. Число в формате Unix или false при неудаче.
Все функции кэшируют результат. Чтобы сбросить кэш используйте функцию 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 "nnchmod()n";
chmod( $file, 0777 );
$__echo();
sleep(1);
echo "nnfile_get_contents()n";
file_get_contents( $file );
$__echo();
sleep(1);
echo "nnfile_put_contents()n";
file_put_contents( $file, 'content2' );
$__echo();
echo "nntouch()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, atime |
file_get_contents() ничего не меняет в этом примере, потому что изменение atime часто отключено на сервере для производительности.
Получим (с кэшем):
Если отключить сброс кэша (закомментировать clearstatcache()), то получим:
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()
|
0 / 0 / 0 Регистрация: 14.12.2015 Сообщений: 4 |
|
|
1 |
|
Как возможно изменить даты создания файлов на сервере? И Возможно ли это?14.12.2015, 14:19. Показов 3038. Ответов 9
Добрый день! Миниатюры
__________________
0 |
|
471 / 399 / 169 Регистрация: 04.01.2013 Сообщений: 1,675 |
|
|
14.12.2015, 14:26 |
2 |
|
Ну судя по всему, логику и впрям всю в сентябре написали, а до февраля Вам внешний вид меняли?)))
0 |
|
12 / 12 / 9 Регистрация: 09.07.2013 Сообщений: 85 |
|
|
14.12.2015, 14:34 |
3 |
|
Скорее всего можно, вопрос в другом является ли авторитетным то, что мы тут напишем.
0 |
|
3803 / 3161 / 1326 Регистрация: 01.08.2012 Сообщений: 10,718 |
|
|
15.12.2015, 01:31 |
4 |
|
Как можно изменять даты создания на сервере, и возможно ли такое? Ну если установить неправильное системное время… почему бы и нет.
0 |
|
14 / 14 / 8 Регистрация: 11.12.2015 Сообщений: 37 |
|
|
15.12.2015, 06:23 |
5 |
|
На unix-серверах дата создания/модификации/последнего доступа к любому файлу легко меняется встроенной утилитой touch. Этим пользуются хакеры чтобы скрыть свои действия на сервере. Добавлено через 6 минут
0 |
|
0 / 0 / 0 Регистрация: 14.12.2015 Сообщений: 4 |
|
|
15.12.2015, 10:11 [ТС] |
6 |
|
Satorius,
0 |
|
14 / 14 / 8 Регистрация: 11.12.2015 Сообщений: 37 |
|
|
15.12.2015, 18:02 |
7 |
|
Настоящие даты создания легко подменить, логи FTP тоже, если вы сисадмин. Хостинг, поди, этой же веб-студии и принадлежит? Тогда они могут любые даты файлов сделать. То что модуль статистики был вставлен в 2014 году не значит что он работал. Куда выгружались/отправлялись результаты этой статистки, она должна быть с датами. Как справедливо заметили выше, экспертное заключение уже есть и суд поверит ему. В принципе, можно опровергать и заключение эксперта, особенно если он как-то аффилирован с этой веб-студией.
0 |
|
0 / 0 / 0 Регистрация: 14.12.2015 Сообщений: 4 |
|
|
15.12.2015, 18:19 [ТС] |
8 |
|
Да, хостинг принадлежит им.
0 |
|
0 / 0 / 0 Регистрация: 14.12.2015 Сообщений: 4 |
|
|
15.12.2015, 18:44 [ТС] |
9 |
|
Satorius, Тут еще кое что всплыло. 29 сентября, в ту дату что указана в экспертизе, мой сайт и наверное весь хостинг подвергся вирусной атаке. Вирусов с моей стороны не было и быть не могло.Проблема была у разработчиков. Может такая ситуация с вирусом как-то повлиять на изменение дат файлов? Миниатюры
0 |
|
14 / 14 / 8 Регистрация: 11.12.2015 Сообщений: 37 |
|
|
15.12.2015, 19:05 |
10 |
|
Да, часто вирусы меняют дату заражённых файлов на старую, чтобы их трудно было обнаружить. Но поскольку хостинг принадлежит веб-студии, их админы могут менять даты файлов как им заблагорассудится, и исправлять любые логи — это простые текстовые файлы.
0 |
В php я могу изменить последнюю модификацию файла и время доступа с помощью touch()
<?php
touch($filename,mktime(0,0,0,2010,1,10));
… но как изменить время создания?
Зачем мне это нужно? Ну, если я обновляю файл или каталог mtime до даты создания, explorer.exe покажет мне более новую дату создания.
22 июнь 2012, в 01:37
Поделиться
Источник
2 ответа
Mh, неудовлетворительный, но рабочий подход, о котором я узнал, заключается в следующем: используя nircmd.
Nircmd — утилита 37kb. (распространяемый, закрытый, бесплатный)
Как действовать:
<?php
$time=strftime('%d-%m-%Y %H:%M:%S',$time);
$cmd=".\nircmdc.exe setfilefoldertime "$filename" "$time"";
system($cmd);
Примечания:
- nircmdc.exe — это версия командной строки nircmd (обратите внимание на дополнительный
cдо.exe) - setfilefoldertime — подкоманда nircmd, она задокументирована здесь.
Тем не менее, я надеюсь, что есть решение COM или WMIC, которое я не мог найти на этот раз.
ZJR
22 июнь 2012, в 02:37
Поделиться
Попробуйте это, вы можете изменить время создания файла и изменить время
Win32 Console ToolBox 1.1
exec('touch.exe /c /t "file.html" '. date('H:i:s'));
nircmdc → — мощный
user956584
30 дек. 2016, в 23:47
Поделиться
Ещё вопросы
- 1Нажмите вопрос в Android
- 0получение значений с помощью метода post из клонированного поля
- 1Шатёр в андроид
- 1Проблема с vue.js для получения данных из REST API
- 1Socket.Send, сервер получает много неверных MPacket
- 0Установка GCC на Windows
- 1Внедрение модели Keras на веб-сайт с помощью Keras.js
- 1Замена значений в массиве Numpy на основе перестановок
- 0Метод jQuery .css не выполняется
- 1Записывая двоичные файлы в Python 3, почему я не получаю шестнадцатеричное представление 9,10 и 13?
- 0создание многоуровневого фрагмента документа
- 0используя любое условие, кроме первичного ключа в предложении «где» в MySQL
- 1Обработка карт всегда вне границ
- 0Перезапись URL с использованием include не загружает таблицу стилей
- 1Как запустить встроенное приложение из приложения
- 0Как я могу отправить ссылку на угловую директиву модели, а не скопировать
- 1Настройка цвета фона элемента списка теряет подсветку
- 1Несколько текстовых режимов в ASP.NET
- 0Как выяснить тип изображения перед его загрузкой?
- 1повторить элементы галереи
- 0AngularJs ng-repeat не обновлялся после изменения переменной $ scope
- 1Тестирование обработки обещаний в JavaScript не работает
- 1Android: как использовать мой файл
- 1Менеджер тегов Google — иногда не устанавливается в пользовательском Javascript
- 0Как избежать событий на элементах позади других в HTML и JavaScript / jQuery
- 0Разбор многомерного массива в PHP
- 0Угловой стол к CSV
- 0Письмо получено поздно EC2 PHP
- 0Найти первый элемент в иерархии, а не в дочерних
- 0Обработка кодирования / декодирования B64 в случае, если данные не кратны 3
- 1Проблема, связанная с жизненным циклом деятельности
- 1Python: для цикла в диапазоне по файлам
- 0Вставка значений в базу данных с использованием PDO в Jquery AJAX PHP
- 0iFrame не загружает IE 8 [дубликаты]
- 1Таймер C # не работает
- 0Как очистить URL после перенаправления входа в Facebook .. PHP
- 0Контент, который изменяет ширину с помощью анимированной боковой панели
- 1Событие срабатывает, когда скрытая форма показывается
- 0Открытие Аккордеонной Панели по якорной ссылке на той же странице и на внешней странице
- 0Uncaught исключение «Google_Auth_Exception» с сообщением «Неверный код»
- 0Переключение области отображения Javascript
- 1Как сохранить изменения в свойствах навигации с помощью Entity Framework
- 0Каков наилучший способ устранения ошибки ограничения внешнего ключа
- 1MVC @ Html.ActionLink no-op от контроллера
- 0Вырезать «Массив» из почтовой информации
- 0php base64_encode и glob не могут заставить работать
- 1peewee ArrayField of UUIDS
- 0логическое выражение if и else для кнопки переключения
- 1Ошибка в AndroidManifest.xml
- 1Здравствуйте, добавление различных изображений в строки в ListView


