Skip to content

Instantly share code, notes, and snippets.

@24HOURSMEDIA
Created January 28, 2019 15:50
Show Gist options
  • Save 24HOURSMEDIA/cfd9ca85e8ae3aa0e42aca10cb060c2c to your computer and use it in GitHub Desktop.
Save 24HOURSMEDIA/cfd9ca85e8ae3aa0e42aca10cb060c2c to your computer and use it in GitHub Desktop.
Some quick examples in php to read and store data and files on AWS S3
<?php
// assume aws sdk is in composer: "aws/aws-sdk-php": "^3.0",
require __DIR__ . '/../../vendor/autoload.php';
// load $AWS_KEY, $AWS_SECRET
require __DIR__ . '/../../local/credentials.php';
$bucket = 'BUCKETNAME'
$awsCredentials = new \Aws\Credentials\Credentials($AWS_KEY, $AWS_SECRET);
/**
* @link https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.S3.S3Client.html
*/
$s3Client = new \Aws\S3\S3Client([
'region' => 'eu-central-1',
'version' => '2006-03-01',
'signature_version' => 'v4',
'credentials' => $awsCredentials
]);
/**
* STORE DATA
*/
// there are two buckets, kbee-data-prod and kbee-data-staging
;
$data = 'test ' . date('Y-m-d H:i:s');
$key = 'testdata/mystring.txt';
$s3Client->putObject([
'Key' => $key,
'Bucket' => $bucket,
'Body' => $data
]);
echo "Data stored\n";
/**
* GET DATA
*/
$key = 'testdata/mystring.txt';
$result = $s3Client->getObject([
'Key' => $key,
'Bucket' => $bucket
]);
$retrievedData = $result->get('Body');
echo "Data retrieved: {$retrievedData}\n";
/**
* STORE FILE
*/
$data = 'test ' . date('Y-m-d H:i:s');
$key = 'testdata/myfile.txt';
$file = __DIR__ . '/myfile.txt';
$s3Client->putObject([
'Key' => $key,
'Bucket' => $bucket,
'SourceFile' => $file
]);
echo "File uploaded\n";
/**
* DOWNLOAD FILE
*/
$key = 'testdata/myfile.txt';
$destFile = __DIR__ . '/mydownloadedfile.txt';
$s3Client->getObject([
'Key' => $key,
'Bucket' => $bucket,
'SaveAs' => $destFile
]);
echo "File downloaded, contents is " . file_get_contents($destFile) . "\n";
echo "done";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment