0

I want to make filesize(), a dynamic filesize. What does it mean?

I mean, when I give it a link and the link is dynamic, too. The filesize() will calculate the size of file in Kb, Mb and Gb.

My link is dynamic I just want the filesize() in converted of Mb and Gb. I want it for URLs.

halfer
  • 19,824
  • 17
  • 99
  • 186
Itz Erfan
  • 31
  • 8

1 Answers1

3

This will do the trick

You can also pass a precision, maybe you want this to be 0.

<?php

function human_filesize($size, $precision = 2) {
    $units = ['B','kB','MB','GB','TB','PB','EB','ZB','YB'];
    $step = 1024;
    $i = 0;
    while (($size / $step) > 0.9) {
        $size = $size / $step;
        $i++;
    }
    return round($size, $precision).$units[$i];
}

function getFileSizeFromUrl($url){
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, TRUE);
    curl_setopt($ch, CURLOPT_NOBODY, TRUE);

    $data = curl_exec($ch);
    $size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);

    curl_close($ch);
    return human_filesize($size);
}

echo getFileSizeFromUrl(" YOUR URL HERE ");
Niels Prins
  • 535
  • 2
  • 11
  • It does not working, I putted a URL and it's giving error Check here: https://blackmovie.xyz/Test, I just changed echo human_filesize('https://m.media-amazon.com/images/M/MV5BMjA4NDI0MTIxNF5BMl5BanBnXkFtZTYwNTM0MzY2._V1_UY1200_CR90,0,630,1200_AL_.jpg'); – Itz Erfan Mar 12 '20 at 11:03
  • Yes this only works with local files. Your said "No I just want to be converted..." – Niels Prins Mar 12 '20 at 11:05
  • Is there anyway to get it for URLs?! – Itz Erfan Mar 12 '20 at 11:06