Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Generate temporary URLs of AWS S3 files in Laravel

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',
    ]
);
Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?