Skip to content

Instantly share code, notes, and snippets.

@keithweaver
Last active May 29, 2023 11:05
Show Gist options
  • Save keithweaver/87c5af35f70aac32b4e621fc9fa3b568 to your computer and use it in GitHub Desktop.
Save keithweaver/87c5af35f70aac32b4e621fc9fa3b568 to your computer and use it in GitHub Desktop.
Open AWS S3 File Privately with PHP
<?php
$BUCKET_NAME = '';
$IAM_KEY = '';
$IAM_SECRET = '';
require '/vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
// Get the access code
$accessCode = $_GET['c'];
$accessCode = strtoupper($accessCode);
$accessCode = trim($accessCode);
$accessCode = addslashes($accessCode);
$accessCode = htmlspecialchars($accessCode);
// Connect to database
$con = ...
// Verify valid access code
$result = mysqli_query($con, "SELECT * FROM s3Files WHERE code='$accessCode'") or die("Error: Invalid request");
if (mysqli_num_rows($result) != 1) {
die("Error: Invalid access code");
}
// Get path from db
$keyPath = '';
while($row = mysqli_fetch_array($result)) {
$keyPath = $row['s3FilePath'];
}
// Get file
try {
$s3 = S3Client::factory(
array(
'credentials' => array(
'key' => $IAM_KEY,
'secret' => $IAM_SECRET
),
'version' => 'latest',
'region' => 'us-east-2'
)
);
//
$result = $s3->getObject(array(
'Bucket' => $BUCKET_NAME,
'Key' => $keyPath
));
// Display it in the browser
header("Content-Type: {$result['ContentType']}");
header('Content-Disposition: filename="' . basename($keyPath) . '"');
echo $result['Body'];
} catch (Exception $e) {
die("Error: " . $e->getMessage());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment