underscore
underscore

Reputation: 6887

how to catch file changes in php

I'm about to develop an application where we can synchronize file changes between two folders.

Ex: I have a folder called FOLDER1 and i'll make a copy of FOLDER1 as FOLDER2 in another directory

/var/www/FOLDER1
/var/www/FILE/FOLDER2 (Same content as FOLDER1)

Then i'll change some files in FOLDER1 and i want to make that effect to the FOLDER2 also(Any synchronization method).is that possible using php ?

Upvotes: 1

Views: 105

Answers (2)

Justin Mitchell
Justin Mitchell

Reputation: 304

In pseudo code terms, you can create an algorithm that might look like:

$foldera = getfolderlist('/path/to/folder/a');
$folderb = getfolderlist('/path/to/folder/b');

// same number of files
if (count($foldera) != count($folderb)) {
    sync();
    return;
}


foreach ($foldera as $file) {
    // file in folder a must be in folder b
    if (!in_array($file, $folderb)){
        sync();
        return;
    }

    // if file is different modification time
    if ($folderb[$file->name]->modifytime != $file->modifytime) {
        sync();
        return;
    }

    // if md5 doesnt match
    if (md5(filecontents($folderb[$file->name])) != md5(filecontents($file))) {
        sync();
        return;
    }
}

Please keep in mind this is pseudo code and won't work if you copy + paste is directly.

Upvotes: 0

hoangvu68
hoangvu68

Reputation: 865

Seem that is very complex to do. But the simple idea is use hash file. In every file we need get hash of that file. And we will sync when hash file changed. We can use md5() as hash function.

Upvotes: 1

Related Questions