AWS Developer Tools Blog
Transferring Files To and From Amazon S3
A common question that I’ve seen on our PHP forums is whether there is an easy way to directly upload from or download to a local file using the Amazon S3 client in the AWS SDK for PHP.
The typical usage of the PutObject
operation in the PHP SDK looks like the following:
use AwsCommonAws; $aws = Aws::factory('/path/to/your/config.php'); $s3 = $aws->get('S3'); $s3->putObject(array( 'Bucket' => 'your-bucket-name', 'Key' => 'your-object-key', 'Body' => 'your-data' ));
The Body
parameter can be a string of data, a file resource, or a Guzzle EntityBody object. To use a file resource, you could make a simple change to the previous code sample.
$s3->putObject(array( 'Bucket' => 'your-bucket-name', 'Key' => 'your-object-key', 'Body' => fopen('/path/to/your/file.ext', 'r') ));
The SDK also provides a shortcut for uploading directly from a file using the SourceFile
parameter, instead of the Body
parameter.
$s3->putObject(array( 'Bucket' => 'your-bucket-name', 'Key' => 'your-object-key', 'SourceFile' => '/path/to/your/file.ext' ));
When downloading an object via the GetObject
operation, you can use the SaveAs
parameter as a shortcut to save the object directly to a file.
$s3->getObject(array( 'Bucket' => 'your-bucket-name', 'Key' => 'your-object-key', 'SaveAs' => '/path/to/store/your/downloaded/file.ext' ));
The SourceFile
and SaveAs
parameters allow you to use the SDK to directly upload files to and download files from S3 very easily.
You can see more examples of how to use these parameters and perform other S3 operations in our user guide page for Amazon S3. Be sure to check out some of our other helpful S3 features, like our MultipartUpload helper and our S3 Stream Wrapper, which allows you to work with objects in S3 using PHP’s native file functions.