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.

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

Читайте также:  Python requests ajax запрос

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 отслеживает изменения файлов и выполняет последующие операции

Я недавно изучаю язык C, мне нужно каждый раз писать vim под Linux :w Сохраните тогда gcc xx.c && ./a.out Слишком много проблем. Я просто подумал об этом. Я написал сценарий для мониторинга определенного каталога. Когда я закончил писать файл языка C, когда я его сохранил, я напрямую вызвал соответствующую функцию и написал монитор, используя цикл while. Изначально я хотел использовать расширения Swoole_timer и inotify для написания скрипта. Подумав об этом, пока этого достаточно, просто сделайте это, не говорите ерунды, просто перейдите к коду

 // слушаем интервал по умолчанию $interval = 3; // отслеживать путь $path = null; $options = getopt('t:h', [ 'help', // справочная информация 'watch::' // Обнаруживаемые каталоги, разделенные запятыми ]); foreach ($options as $option => $value)  switch ($option)  case 'help': case 'h': $manual = < Description: -h, --help Know how to use -t The path to be detected can be separated by a comma, and the default value is 3 --watch Specify the folder you want to listen to, multiple folders separated by commas, using an absolute path EOF; fwrite(STDIN, $manual, mb_strlen($manual)); fgets(STDIN); fclose(STDIN); exit; case 't': $interval = $value; break; case 'watch': $path = explode(',', $value); foreach ($path as $pathItem)  $realPath = realpath($pathItem); if (!is_dir($realPath))  $tips = "The specified $pathItem> path does not exist\n"; fwrite(STDIN, $tips, mb_strlen($tips)); fgets(STDIN); fclose(STDIN); exit; > > break; default: $tips = 'Unsupported parameters'; fwrite(STDIN, $tips, mb_strlen($tips)); fgets(STDIN); fclose(STDIN); break; > > if (!isset($path))  $tips = "Specify the folder you want to listen to, multiple folders separated by commas, using an absolute path\n"; fwrite(STDIN, $tips, mb_strlen($tips)); fgets(STDIN); fclose(STDIN); exit; > function scanDirectory($paths)  $result = []; $collections = []; while ($element = array_pop($paths))  $element = realpath($element); if (is_dir($element))  $pathElements = scandir($element); $pathElements = array_filter($pathElements, function ($e)  return !in_array($e, ['.', '..']); >); foreach ($pathElements as $pathElement)  $pathElement = $element . DIRECTORY_SEPARATOR . $pathElement; if (is_dir($pathElement))  array_push($paths, $pathElement); > else  array_push($collections, $pathElement); > > continue; > array_push($collections, $element); > if (!$collections)  return []; > array_walk($collections, function ($e) use (&$result)  $result[$e] = md5_file($e); >); return $result; > while (true)  static $previousFile = null; usleep($interval * 1000 * 1000); $files = scanDirectory($path); if (is_null($previousFile))  $previousFile = $files; > $changedFiles = array_diff_assoc($files, $previousFile); $previousFile = $files; // Найдя измененный файл, выполняем следующие операции, следующий код можно удалить самостоятельно и переписать свой бизнес if ($changedFiles)  foreach ($changedFiles as $filePath => $hash)  // Не обрабатывать текст Swp if (pathinfo($filePath)['extension'] == 'swp') continue; $cmd = "gcc $filePath> && ./a.out"; $response = shell_exec($cmd); echo $response . PHP_EOL; echo "------------------------------------------------------------------------\n"; > > > 

Все написано на родном PHP, очень простой инструмент
Предыдущее описание опции -h, -help, —watch, -t было написано

Разместите несколько изображений, чтобы почувствовать
Вставьте приведенный выше код в dev.php В следующем примере dev.php
php dev.php —watch=/root/c/pointer,/root/c/scope -t=1
означает мониторинг /root/c/pointer , /root/c/scope Эти два каталога сканируются каждую секунду, чтобы увидеть, были ли обновлены какие-либо файлы.

Вы также можете использовать аналогичные идеи для синхронизации файлов, защиты от взлома веб-сайтов и других функций, но вам нужно расширить функции самостоятельно. Я здесь сегодня, спи ~~

Источник

предупреждение при изменении файла

здравствуйте. как следить за текстовым файлом и когда он будет изменён выдать предупреждение. звук с окошком сообщения о изменениях.

Как отредактировать системные файлы на сервере при любом изменении txt файла на сайте?
У меня есть такая задача. На сайте в корне лежит txt файл fail.txt, в который иногда добавляется.

PHP + XML — изменении файла .xsd (XLM Shema).
До файла .XML при помощи PHP получается добраться. Но когда создаю новый тег в .xml, возникает.

Звук при изменении данных в бд
Доброе время суток, форумчане! Может кто знает как сделать проверку бд на наличие новых строк и.

после закрытия предупреждения чтобы уже по новому проверял. следующее изменение.

ЦитатаСообщение от andreus Посмотреть сообщение

Выполнение php при изменении формы
Есть форма которая состоит допустим из чекбоксов. И есть рядом с формой блок, где выводится некая.

Прозрачность в gif при изменении размера
Всем привет. Есть gif с прозрачным фоном, нужно уменьшить картинку и сохранить без потери.

Исчезновение блока при изменении окна
Как убрать блок при изменении окна браузера как это реализовать? <script> width=screen.width;.

Создаем события при изменении checkbox
Надо создать событие на checkbox даный варин работае: <script type="text/javascript"> .

Источник

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

Источник

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