Bunny CDN storage API with PHP

Like all great services Bunny CDN has an API. Making use theoretically easier.  The storage API allows you to upload files, delete files and list files/directories. I’m interested in the listing of files in the storage zone. With the API I can check files have already been uploaded, their size, format and even the date/time they got uploaded.

The default Bunny CDN API returns the uploaded (created) time in ISO 8601 time format, which isn’t compatible with PHP date and time functions. Also returned is the file size as raw bytes not quite as handy to having it in formatted MB and GB.

I addressed these issues in this PHP file. Thanks to a format size units function i got off stack overflow I made a simple function to remove the unnecessary data returned from the API and format it so you can see the simple file name and its extension. Converting the ISO 8601 time stamp into a PHP compatible one makes sorting by upload date easy.

bunnycdn_storage.php
<?php
header("Content-type:application/json");
function storage($key, $dir = ''){
    return json_decode(file_get_contents("https://storage.bunnycdn.com/".$dir."/?AccessKey=".$key.""),true);
}
function formatSizeUnits($bytes)
{
    if ($bytes >= 1073741824)
    {
        $bytes = number_format($bytes / 1073741824, 2) . ' GB';
    }
    elseif ($bytes >= 1048576)
    {
        $bytes = number_format($bytes / 1048576, 2) . ' MB';
    }
    elseif ($bytes >= 1024)
    {
        $bytes = number_format($bytes / 1024, 2) . ' KB';
    }
    elseif ($bytes > 1)
    {
        $bytes = $bytes . ' bytes';
    }
    elseif ($bytes == 1)
    {
        $bytes = $bytes . ' byte';
    }
    else
    {
        $bytes = '0 bytes';
    }
    return $bytes;
}
$array = storage('STORAGE-PASSWORD-HERE','STORAGENAME/');
$items = array('data' => array());
foreach ($array as $value){
    $date = $value['DateCreated'];
    $fixed_date = date('Y-m-d H:i:s', strtotime($date));
    $file_name = explode('.', $value['ObjectName']);
    $file_name = $file_name[0];
    $file_type = substr($value['ObjectName'], strpos($value['ObjectName'], ".") + 1);
    $size = formatSizeUnits($value['Length']);
    $raw_size = $value['Length'];
    $guid = $value['Guid'];
    $items['data'][] = array('name' => $file_name, 'file_type' => $file_type, 'size' => $size, 'raw_size' => $raw_size, 'datetime' => $fixed_date, 'guid' => $guid);
}
echo json_encode($items);