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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago