📅  最后修改于: 2023-12-03 15:17:12.918000             🧑  作者: Mango
In Laravel, we can generate pre-signed URLs for S3 buckets using the AWS SDK for PHP. S3 pre-signed URLs are typically used to grant temporary access to private files stored in S3.
This feature can be very useful for a variety of use cases, including downloading files from S3 over HTTP/HTTPS without requiring the client to have AWS credentials.
First, we need to install the required packages:
composer require aws/aws-sdk-php
Next, we will need to configure the AWS SDK. The most common way to do this is by defining the necessary environment variables:
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=
AWS_BUCKET=
Alternatively, we can create a new S3 client instance with the needed configuration:
$s3 = new Aws\S3\S3Client([
'version' => 'latest',
'region' => env('AWS_DEFAULT_REGION'),
'credentials' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
]
]);
To generate a pre-signed URL for an S3 object, we can use the getCommand
method on the S3 client:
$cmd = $s3->getCommand('GetObject', [
'Bucket' => env('AWS_BUCKET'),
'Key' => 'path/to/object',
'ResponseContentType' => 'application/octet-stream'
]);
$presignedUrl = $s3->createPresignedRequest($cmd, '+10 minutes')->getUri()->__toString();
This code will generate a URL that can be used to download the S3 object at the given path. The createPresignedRequest
method takes two arguments: the S3 command that we want to pre-sign, and a time interval (expressed as a string) for which we want the link to be valid.
The resulting URL will remain valid for the duration of the specified time interval.
Generating pre-signed URLs for S3 buckets is an important feature that can be used to grant temporary access to private files stored in S3. It can be used to allow users to download files without needing to have AWS credentials, or to embed files in web pages or emails.
In this tutorial, we have seen how to generate pre-signed URLs using the AWS SDK for PHP in Laravel. We hope this tutorial has been helpful!