I’ve been playing with the Amazon S3 PHP Class and noticed the stored files were corrupted every time I used the putObject() function. The answer was deceptively simple: run the file through the inputFile() function and it’ll all be good.

The Amazon S3 PHP Class is a really simple and easy to understand solution for sending files to Amazon S3 and I’ve been using it to send files from my web server. As per the examples, I was using the putObjectFile() function to achieve this but there are a few problems:

  1. It’s a Legacy function.
  2. It does not allow me to set the Storage Class of the file (it defaults to Standard Storage)

Fortunately the class also provides the putObject() function which allows you to define the Storage Class. And if you dig through the code you’ll find that putObjectFile() actually uses the putObject() function anyway. So it’s win-win. I replaced my call to the putObject() function with this:

S3::putObject( $file_path, $aws_bucket, $amazon_file_path, S3::ACL_PRIVATE, array(), null, S3::STORAGE_CLASS_RRS

… which didn’t work. The file would be sent to Amazon S3 but it would be corrupted and unusable.

Eventhough the documentation says that $file_path can be a string, I’ve found this doesn’t work. You have to send $file_path through the inputFile() function. So the correct code would look like this:

S3::putObject( S3::inputFile( $file_path ), $aws_bucket, $amazon_file_path, S3::ACL_PRIVATE, array(), null, S3::STORAGE_CLASS_RRS

This made everything good again.

Note the class also has a inputResource() function which I assume is for uploading other resources that are not files.