Last active
May 29, 2023 11:05
-
-
Save keithweaver/87c5af35f70aac32b4e621fc9fa3b568 to your computer and use it in GitHub Desktop.
Open AWS S3 File Privately with PHP
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 | |
$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