Marty Wallace
Marty Wallace

Reputation: 35734

PHP - auto detect when/if files have been updated

Is there a way in PHP to detect when a file is updated and saved?

If not what would be the best method 'faking' this.

I.e. before a certain action if executed, check the last saved date of the file?

Upvotes: 3

Views: 10081

Answers (5)

NVRM
NVRM

Reputation: 13067

A simple way can be to watch for a content change using a hash of the type crc32, who have the advantage to have a very low footprint.

<?php
$hash = hash_file("crc32","watch.txt");
while ($hash === hash_file("crc32","watch.txt")){
  usleep(100000); // 100ms
}
echo "File changed";

https://en.wikipedia.org/wiki/Cyclic_redundancy_check

A Cyclic Redundancy Check (CRC) (...) Blocks of data entering these systems get a short check value attached, based on the remainder of a polynomial division of their contents. On retrieval, the calculation is repeated and, in the event the check values do not match, corrective action can be taken

List of algos: https://www.php.net/manual/en/function.hash-algos.php

Upvotes: 2

user1359600
user1359600

Reputation:

<?php
// 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));
}

?>

Use this function to get when file was last modified. You can play with data to achieve your task.

Upvotes: 2

craig1231
craig1231

Reputation: 3867

A PHP script would not be able to automatically detect changes to files because the page has to be requested. You could write a script and run a cron (scheduled task) to run every so often. Or use filemtime() as others have suggested.

Upvotes: 4

Ry-
Ry-

Reputation: 224905

You can use filemtime. It returns a file's "last modified" timestamp. (If you mean running a PHP script when a file is changed, that's not possible using just PHP.)

Upvotes: 3

PeeHaa
PeeHaa

Reputation: 72672

You can use filemtime() to find out the modification date of a file. If I understood you correct.

However if you want to keep track of files when they are changed you can still use filemtime, but you will have to keep track of the current modified date (e.g. in db or file) and check this value against the current value.

You could use a cronjob to periodically run this php script.

Upvotes: 2

Related Questions