Generate temporary URLs of AWS S3 files in Laravel

Amit Merchant · November 2, 2020 ·

Sometimes, all you want to do is generate temporary URLs for files that you have stored on your AWS S3 bucket. For instance, you would want to use this to prevent hotlinking of images.

The temporaryUrl method

Laravel provides an easy way to do so. To create temporary URLs of files, all you need to do is use the temporaryUrl on the Illuminate\Support\Facades\Storage facade like so.

use Illuminate\Support\Facades\Storage;

$url = Storage::temporaryUrl(
    'secret.pdf', now()->addMinutes(5)
);

As you can tell, the temporaryUrl method accepts two mandatory parameters.

  • The path of the file.
  • A DateTime instance specifying when the URL should expire.

The above code will generate a temporary URL of the file which will get expired in 5 minutes.

Under the hood, Laravel uses the AWS SDK to create pre-signed URLs which are nothing but temporary URLs in the AWS world.

Add more request parameters

You can also pass additional S3 request parameters in form of an array as the third (optional) argument to the temporaryUrl method to add more control on file requests like so.

use Illuminate\Support\Facades\Storage;

$url = Storage::temporaryUrl(
    'secret.pdf', 
    now()->addMinutes(5),
    [
        'ResponseContentType' => 'application/octet-stream',
        'ResponseContentDisposition' => 'attachment; filename=file2.jpg',
    ]
);

Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!