Dynamically Sync Your Files With Amazon S3

I’ve been getting used to using the cloud over the past week or so and I’ve got to say it’s much easier to manage than I had imagined. I know there are tons of great desktop clients to manage your S3 buckets and files, but I wanted something to do all of the management for me – to make things simple.

I’ve put together a script using Undesigned’s awesome PHP S3 class that will scan a directory, compare all of the files in the directory to those in a given directory on your bucket and then upload missing files or replaced unmatched files.

You could set this PHP script up to do a lot more than it does currently, as it was set up to be a quick and dirty solution. Here’s the basis of it. You can download the full script and classes below.

  1. //check to see if the file exists and can return file info
  2. if (($info = $s3->getObjectInfo($bucket, $uri)) !== false) {
  3. //if the local hash doesnt match the remote hash, upload and replace the file
  4. if($info[‘hash’] <> $local_md5){
  5. print_r(‘Can\’t match file: ‘.$the_file.‘ — Now uploading’);
  6. echo "Putting $the_file . . . at $uri ";
  7. //this will upload files with private permissions – you need to set the permissions as
  8. //needed by changing S3::PRIVATE to whichever level you need.
  9. if($s3->putObject(S3::inputFile($object), $bucket, $uri,  S3::ACL_PRIVATE,
  10. array( // Custom $requestHeaders
  11. "Cache-Control" => "max-age=315360000",
  12. "Expires" => gmdate("D, d M Y H:i:s T", strtotime("+5 years"))
  13. )))
  14. echo "OK\n";
  15. else
  16. echo "ERROR!\n";
  17. }
  18. else{
  19. echo "The hash values for $the_file are equal ";
  20. }
  21. }else{
  22. //file doesn’t exist in your bucket, so upload it
  23. print_r(‘Can\’t find that file: ‘.$the_file.‘ — Now uploading’);
  24. echo "Putting $the_file . . . at $uri ";
  25. if($s3->putObject(S3::inputFile($object), $bucket, $uri,  S3::ACL_PUBLIC_READ,
  26. array( // Custom $requestHeaders
  27. "Cache-Control" => "max-age=315360000",
  28. "Expires" => gmdate("D, d M Y H:i:s T", strtotime("+5 years"))
  29. )))
  30. echo "OK\n";
  31. else
  32. echo "ERROR!\n";
  33. }
Get the Class Get the sync script
Be Sociable, Share!