[Drupal] How to upload images to Amazon S3 via code in Drupal

| | 1 min read

This article is on how to add images to Amazon S3 in a drupal site(D7) via code. For this, download drupal module Amazon S3 (https://www.drupal.org/project/amazon_s3). The purpose of this module is to get the s3.inc file (the file which define all s3 functions defined in Amazon)

After enabling this module you have to set the API configuration on admin/settings/Amazon-s3

Note : To set these API key you register an Amazon account(http://aws.amazon.com/s3/) and generated API keys

Then create a new bucket via drupal (admin/structure/Amazon-s3) - A folder in our account

Insert the below code to the place where the images generated or uploaded from/to our system

 $input = S3::inputFile('filepath');
S3::putObject($input, 'bucket_name', 'filepath', S3::ACL_PUBLIC_READ); 

To delete image from s3 via code use,

 S3::deleteObject('bucket_name', 'filepath') 

Sometimes we have to set the authentication keys via code like;

 S3::setAuth('AWSAccessKeyId', 'Secret key') 

More details on S3 functions
Refer : http://undesigned.org.za/2007/10/22/amazon-s3-php-class/documentation