Reputation: 63
I have this php file which i use to get downloaded and uploaded data usage from my splynx radius server over API which outputs it as bytes making a very long string which i want to shorten into Mbps and from the arrays that i get from splynx server i would like help to convert the array "in_bytes" and "out_bytes" to MB. This is my whole code below
<?php
$api_url = 'https://xxx/'; // Splynx URL
$admin_login = "xxx"; // administrator login
$admin_password = "xxx"; // administrator password
$api = new SplynxAPI($api_url);
$api->setVersion(SplynxApi::API_VERSION_2);
$isAuthorized = $api->login([
'auth_type' => SplynxApi::AUTH_TYPE_ADMIN,
'login' => $admin_login,
'password' => $admin_password,
]);
if (!$isAuthorized) {
exit("Authorization failed!\n");
}
$customerApiUrl_online = "admin/customers/customers-online";
$customers_params = [
'main_attributes' => [
'status' => ['IN', ['active', 'blocked']]
]];
$result_online = $api->api_call_get($customerApiUrl_online);
$customers_online = $api->response;
?>
<table class="table table-transparent">
<thead>
<tr>
<th>DOWNOAD</th>
<th>UPLOAD</th>
</tr>
</thead>
<tbody>
<?php foreach($customers_online as $item) :?>
<tr>
<td><?php echo $item['in_bytes']; ?></td>
<td><?php echo $item['out_bytes']; ?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
Upvotes: 0
Views: 687
Reputation: 63
I finnaly got it to work using the following to MB
<?php echo round(floatval($item['in_bytes'])/1000000,2); ?>
Upvotes: 0
Reputation: 11943
Converting between them is trivial. It's a simple mathematical operation.
The question is what do you mean by Mbps exactly? Do you mean Mega bits per second? Or Mega bytes per second? There's a significant difference:
function bytesToMbps($bytes) {
$bits = $bytes * 8;
return sprintf("%.2fMbps", $bits / 1000000); // Mega bits per second
}
echo bytesToMbps(1024*1024*97); // 813.69Mbps
Or MBps:
function bytesToMbps($bytes) {
return sprintf("%.2fMbps", $bytes / 1024 / 1024); // Mega bytes per second
}
echo bytesToMbps(1024*1024*97); // 97.00Mbps
More importantly are you only interested in conversion of bytes to Mbps or do you want a general logarithmic conversion function?
function bytesLog($bytes) {
$magnitudes = ["B", "KB", "MB", "GB", "TB", "PB", "EB"];
$mag = log($bytes, 1024);
return sprintf("%.2f%s", $bytes / (1024 ** ((int) $mag)), $magnitudes[(int)$mag]);
}
echo bytesLog(1023); // 1023.00B -- Bytes
echo bytesLog(1024*3); // 3.00KB -- Kilobytes
echo bytesLog(1024*1024*12); // 12.00MB -- Megabytes
echo bytesLog(1024*1024*1024*134); // 134.00GB -- Gigabytes
echo bytesLog(1024*1024*1024*1024*768); // 768.00TB -- Terabytes
echo bytesLog(1024*1024*1024*1024*1024*960); // 960.00PB -- Petabytes
echo bytesLog(1024*1024*1024*1024*1024*1024*512); // 512.00EB -- Exabytes
Upvotes: 1