Skip to content

Instantly share code, notes, and snippets.

@harmenjanssen
Created March 26, 2019 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harmenjanssen/2c8ac040960ca15bc09197fe1caa9ac2 to your computer and use it in GitHub Desktop.
Save harmenjanssen/2c8ac040960ca15bc09197fe1caa9ac2 to your computer and use it in GitHub Desktop.
Create a redirect programmatically in a website-configured S3 bucket.
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_REGION=
AWS_S3_BUCKET=
AWS_BUCKET_WEBSITE_URL=
{
"require": {
"aws/aws-sdk-php": "^3.90",
"vlucas/phpdotenv": "^3.3"
}
}
<?php
require './vendor/autoload.php';
$dotenv = Dotenv\Dotenv::create(__DIR__);
$dotenv->load();
use Aws\Credentials\Credentials;
use GuzzleHttp\Promise;
use Aws\S3\S3Client;
// Custom credentials provider is used to grab credentials from .env.
// This circumvents AWS's magic lookup of env vars and makes us
// more flexible in naming variables et cetera.
function getAwsCredentialsProvider(): callable {
return function () {
return Promise\promise_for(
new Credentials(getenv('AWS_ACCESS_KEY_ID'), getenv('AWS_SECRET_ACCESS_KEY'))
);
};
}
$s3Api = new S3Client([
'region' => getenv('AWS_REGION'),
'version' => 'latest',
'credentials' => getAwsCredentialsProvider(),
'http' => [
'timeout' => 400
]
]);
$from = $_SERVER['argv'][1] ?? null;
$to = $_SERVER['argv'][2] ?? null;
if (!$from || !$to) {
echo 'Insufficient arguments. Usage: php ' . basename(__FILE__) . ' /from /to';
exit(1);
}
// Ensure full URL.
$url = preg_match('/^http/', $to)
? $to
: rtrim(getenv('AWS_BUCKET_WEBSITE_URL'), '/') . '/' . ltrim($to, '/');
var_dump($s3Api->putObject(
[
'Bucket' => getenv('AWS_S3_BUCKET'),
'Key' => ltrim($from, '/'),
'ACL' => 'public-read',
'WebsiteRedirectLocation' => $url
]
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment