Skip to content

Instantly share code, notes, and snippets.

@DustyReagan
Created December 3, 2010 23:39
Show Gist options
  • Save DustyReagan/727727 to your computer and use it in GitHub Desktop.
Save DustyReagan/727727 to your computer and use it in GitHub Desktop.
Creates an Amazon S3 object from a string with PHP
<?php
/**
* Creates an Amazon S3 object from a string
*
* @param $input String (Required) The data to store in the object
* @param $bucket String (Required) Name of the bucket to use.
* @param $filename String (Required) Filename for the object.
* @param $options Array (Optional) An associative array of options specified below.
*
* Supported keys for the $options param:
* objectAcl Constant The ACL settings for the specified object. [Allowed values: `AmazonS3::ACL_PRIVATE`, `AmazonS3::ACL_PUBLIC`, `AmazonS3::ACL_OPEN`, `AmazonS3::ACL_AUTH_READ`, `AmazonS3::ACL_OWNER_READ`, `AmazonS3::ACL_OWNER_FULL_CONTROL`]. Defaults to AmazonS3::ACL_PUBLIC
* compress Boolean Whether to compress the input or not.
* complvl Integer Compression level ranges betweent 0-9 and defaults to 9
* rss Boolean Whether to use Reduced Redundancy storage or not.
* bucketRegion Constant If the bucket wasn't found, it will be created in this region. Defaults to AmazonS3::REGION_US_E1
* bucketAcl Constant same as objectAcl
*
* @returns String Url of the object created
*/
function saveToS3($input, $bucket, $filename, $options = array()) {
$defaults = array(
'objectAcl' => AmazonS3::ACL_PUBLIC,
'compress' => true,
'complvl' => 9,
'rrs' => false,
'bucketRegion' => AmazonS3::REGION_US_E1,
'bucketAcl' => AmazonS3::ACL_PRIVATE
);
$options = array_merge($defaults, $options);
$s3 = new AmazonS3();
if (!$s3->if_bucket_exists($bucket)) {
if (!$s3->create_bucket($bucket, $options['bucketRegion'], $options['bucketAcl'])->isOk()) {
trigger_error('Bucket not found and could not be created', E_USER_NOTICE);
return false;
}
}
if ($options['compress']) {
$input = gzcompress($input, $options['complvl']);
}
$objectOpts = array('body' => $input, 'acl' => $options['objectAcl']);
if ($options['rrs']) {
$objectOpts['storage'] = AmazonS3::STORAGE_REDUCED;
}
$response = $s3->create_object($bucket, $filename, $objectOpts);
if (!$response->isOK()) {
trigger_error('Object could not be created', E_USER_NOTICE);
return false;
}
return $response->header['_info']['url'];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment