Create a gist now

Instantly share code, notes, and snippets.

Registering and using S3 protocol with AWS S3 stream wrapper for PHP
<?php
define('AWS_KEY','YOUR_AWS_KEY_HERE');
define('AWS_SECRET','YOUR_AWS_SECRET_HERE');
require_once('AWSSDKforPHP/sdk.class.php');
require_once('AWSSDKforPHP/extensions/s3streamwrapper.class.php');
$s3 = new AmazonS3(array(
'key' => AWS_KEY,
'secret' => AWS_SECRET,
'default_cache_config' => '',
'certificate_authority' => true
));
S3StreamWrapper::register($s3);
?>
<?php
//rename the object 'foo.txt' to 'bar.txt' in bucket 'myBucket':
//there is no 'rename' method in the API, so we first have to copy the object
//to the new location, and then delete the old one:
$response = $s3->copy_object(
array(
'bucket' => 'myBucket',
'filename' => 'foo.txt'
),
array(
'bucket' => 'myBucket',
'filename' => 'bar.txt'
)
);
if ($response->isOK()){
$response = $s3->delete_object('myBucket', 'foo.txt');
if (!$response->isOK()){
//handle error...
}
}
//read contents of object 'foo/bar.txt' in bucket 'myBucket':
$data = $s3->get_object(
'myBucket',
'foo/bar.txt'
))->body;
//store data in object 'foo/bar.txt' in bucket 'myBucket':
$response = $s3->create_object(
'myBucket',
'foo/bar.txt',
array(
'body' => 'data...'
)
);
?>
<?php
//rename the object 'foo.txt' to 'bar.txt' in bucket 'myBucket':
rename('s3://myBucket/foo.txt', 's3://myBucket/bar.txt');
//delete the object 'bar.txt' from bucket 'myBucket':
unlink('s3://myBucket/bar.txt');
//create a new bucket 'mySecondBucket':
mkdir('s3://mySecondBucket');
//read contents of object 'foo/bar.txt' in bucket 'myBucket':
$data = file_get_contents('s3://myBucket/foo/bar.txt');
//store data in object 'foo/bar.txt' in bucket 'myBucket':
file_put_contents('s3://myBucket/foo/bar.txt', 'data...');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment