Amazon S3 pre-signed URL with AWS SDK for PHP Version 3 - AWS SDK for PHP

Amazon S3 pre-signed URL with AWS SDK for PHP Version 3

You can authenticate certain types of requests by passing the required information as query-string parameters instead of using the Authorization HTTP header. This is useful for enabling direct third-party browser access to your private Amazon S3 data, without proxying the request. The idea is to construct a “pre-signed” request and encode it as a URL that an end-user’s browser can retrieve. Additionally, you can limit a pre-signed request by specifying an expiration time.

The following examples show how to:

All the example code for the AWS SDK for PHP is available here on GitHub.

Credentials

Before running the example code, configure your AWS credentials, as described in Credentials. Then import the AWS SDK for PHP, as described in Basic usage.

Creating a pre-signed request

You can get the pre-signed URL to an Amazon S3 object by using the Aws\S3\S3Client::createPresignedRequest() method. This method accepts an Aws\CommandInterface object and expired timestamp and returns a pre-signed Psr\Http\Message\RequestInterface object. You can retrieve the pre-signed URL of the object using the getUri() method of the request.

The most common scenario is creating a pre-signed URL to GET an object.

Imports

use Aws\Exception\AwsException; use AwsUtilities\PrintableLineBreak; use AwsUtilities\TestableReadline; use DateTime; require 'vendor/autoload.php';

Sample Code

$command = $s3Service->getClient()->getCommand('GetObject', [ 'Bucket' => $bucket, 'Key' => $key, ]);

Creating a pre-signed URL

You can create pre-signed URLs for any Amazon S3 operation using the getCommand method for creating a command object, and then calling the createPresignedRequest() method with the command. When ultimately sending the request, be sure to use the same method and the same headers as the returned request.

Sample Code

try { $preSignedUrl = $s3Service->preSignedUrl($command, $expiration); echo "Your preSignedUrl is \n$preSignedUrl\nand will be good for the next 20 minutes.\n"; echo $linebreak; echo "Thanks for trying the Amazon S3 presigned URL demo.\n"; } catch (AwsException $exception) { echo $linebreak; echo "Something went wrong: $exception"; die(); }

Getting the URL to an object

If you only need the public URL to an object stored in an Amazon S3 bucket, you can use the Aws\S3\S3Client::getObjectUrl() method. This method returns an unsigned URL to the given bucket and key.

Sample Code

$preSignedUrl = $s3Service->preSignedUrl($command, $expiration);
Important

The URL returned by this method is not validated to ensure that the bucket or key exists, nor does this method ensure that the object allows unauthenticated access.