Reputation: 9355
I need to check if a file that existed in a directory on the server is the same file that was there say 5 minutes ago?
On a specific directory, I'm deleting and recreating a file with the same name every few minutes. A script is to access the file say every 2 mins. So at time t, the script checks the file and do stuffs. Then at time t+1, the file is deleted and recreated (same name but maybe different content). Then at time t+2, the script again looks for the file.
So in the second check , is there a way to check whether the file has been changed or not (without having to read the content)??
Upvotes: 4
Views: 9220
Reputation: 37566
Compare the calculated MD5 - this should in dicate any changes to the file
Upvotes: 0
Reputation: 1740
Check the fileinode()
. If the file was deleted and recreated the inode will be different even if the file will get identical content.
Upvotes: 0
Reputation: 3454
I'd check whether the checksum of the file has changed. This one-liner calculates the MD5 hash:
md5(file_get_contents('/path/to/file'))
As an alternative, you could (if the OS and FS supports this) rely on file creation datetime.
Upvotes: 0
Reputation: 437336
From PHP, you can use the function filemtime
to get the last-modified timestamp for your file.
Be careful!
The return value of this function is cached, and calling it multiple times from the same script will result in the same value being returned even if the file has changed in the meantime! To work around this, you need to call clearstatcache
before calling filemtime
.
If you are calling filemtime
once in every script (and then the script terminates), this does not affect you and you don't need to do clearstatcache
.
Upvotes: 5
Reputation: 2468
You can calculate a "fingerprint" of the file using the md5_file() function, which will indicate if the file has been altered.
e.g.
<?php
$file1_fp = md5_file($fname1);
$file2_fp = md5_file($fname2);
if ($file1_fp === $file2_fp )
{
//do something..
}
?>
see: http://php.net/manual/en/function.md5-file.php
Upvotes: 4
Reputation: 895
If you could trust the timestamp, use the File's timestamp to differentiate it, otherwise, use MD5 digest etc or do a bit to bit comparison.
Upvotes: 0
Reputation: 400952
The first idea that comes to mind to determine whether a file has changed is to check its modification time, using the filemtime()
function.
But I'm guessing this will not quite work, as you are deleting and re-creating the file regularly.
In PHP, you'll use one of the following functions, depending on which algorithm you want to work with :
Upvotes: 12
Reputation: 3556
Use filemtime to check the date the file was last modified. http://php.net/manual/en/function.filemtime.php
Upvotes: 2