Created
March 26, 2019 15:27
-
-
Save harmenjanssen/2c8ac040960ca15bc09197fe1caa9ac2 to your computer and use it in GitHub Desktop.
Create a redirect programmatically in a website-configured S3 bucket.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
AWS_ACCESS_KEY_ID= | |
AWS_SECRET_ACCESS_KEY= | |
AWS_REGION= | |
AWS_S3_BUCKET= | |
AWS_BUCKET_WEBSITE_URL= |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"require": { | |
"aws/aws-sdk-php": "^3.90", | |
"vlucas/phpdotenv": "^3.3" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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