Compare the contents of a remote directory with a local directory

Here is a little PHP script I wrote, that you can run from the command line. I wrote it to allow you to see what files are in a remote folder that are not in a local folder.

user@localhost the_directory> php compare.php the_host_address.com:/the/remote/dir/ /the/local/dir/

This would be used when you copy files from a remote directory to your local and then you might want to see what files did not transfer due to errors. Perhaps after you download you want to monitor the folder on the server to determine if there has been any new files added. If you want to keep two folders in sync it is recommend that you use the Linux command rsync. You can actually use rsync to look at the differences between two folders but it compares if the file has changed, if its permissions are different etc. etc. This script just compares the file lists of the remote and local folders. In other words it is only looking at the folder contents not the file contents or file properties.

Here is the code for the compare.php file:

<?php
/**
* See what is missing in a local directory that exists in a remote directory
* To use, run the following command at the Linux command prompt
* php compare.php the_host_address.com:/the/remote/dir/ /the/local/dir/
**/
if (count($argv) < 2){
die("No arguments stated");
}
if (count($argv) < 3){
die("Two arguments required");
}
//parse arguments
//ex: $argv[1] = 'the_host_address.com:/the/remote/dir/';
list($remote_host,$remote_dir) = explode(":",$argv[1]);
//ex: $argv[2] = '/the/local/dir/';
$local_dir = $argv[2];

//get username
$cmd_get_username = "whoami";
$username = exec($cmd_get_username);

//get remote file list
$cmd_get_remote_list = "ssh $username@$remote_host 'cd $remote_dir;find .'";
$remote_output = array();
exec($cmd_get_remote_list,$remote_output);

//get local file list
$cmd_get_local_list = "cd $local_dir; find .";
$local_output = array();
exec($cmd_get_local_list,$local_output);

$differences_list = array_diff($remote_output,$local_output);

foreach ($differences_list as $val){
echo $val."\n";
}
?>

comments powered by Disqus