Categories: Development

How to do token authentication URLs with BunnyCDN

How to generate URL authentication tokens and expiry with PHP on BunnyCDN (Bunny Net) URLs.

This means that URL’s fetched that do not have a valid token and expiry will return a 403 HTTP response.

Using token authentication on URLs makes traffic need to go through your website rather than directly accessing the media.

Here is a PHP function created with details from the Bunny net blog post.

function URLTokenGenerate(string $path, string $zone_url, int $expires_seconds = 3600): string
{
    $security_key = 'URL-TOKEN-AUTH-KEY-HERE';
    $expires = (time() + $expires_seconds);
    $hash_base = $security_key . $path . $expires;
    $token = md5($hash_base, true);
    $token = base64_encode($token);
    $token = strtr($token, '+/', '-_');
    $token = str_replace('=', '', $token);
    return "{$zone_url}{$path}?token={$token}&expires={$expires}";
}

Put in your token authentication key at $security_key

An example call:

$url = URLTokenGenerate('/images/banner.jpg', 'https://myweb.b-cdn.net', 300);

Will return similar to

https://myweb.b-cdn.net/images/banner.jpg?token=_AWA1k7ukqLqx2EyXUhrHA&expires=1627651686

This URL will be valid until 5 minutes (300 seconds) after creation.

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago