Skip to content

Instantly share code, notes, and snippets.

@finalwebsites
Created January 30, 2016 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save finalwebsites/9e60dc136a0095ea14cc to your computer and use it in GitHub Desktop.
Save finalwebsites/9e60dc136a0095ea14cc to your computer and use it in GitHub Desktop.
PHP Filesize with label - This custom PHP function reads the file size from a selected file and convert the number of bytes into KB, MB etc. Just define the file name, the file path and the size is returned by the function.
<?php
function file_size($file, $path = "") {
define("DOCUMENT_ROOT", dirname(__FILE__); // better you define this in the root
$bytes = array("B", "KB", "MB", "GB", "TB", "PB");
$file_with_path = DOCUMENT_ROOT."/".$path."/".$file;
// replace (possible) double slashes with a single one
$file_with_path = str_replace("//", "/", $file_with_path);
$size = filesize($file_with_path);
$i = 0;
while ($size >= 1024) { //divide the filesize (in bytes) with 1024 to get "bigger" bytes
$size = $size/1024;
$i++;
}
if ($i > 1) {
// you can change this number if you like (for more precision)
return round($size,1)." ".$bytes[$i];
} else {
return round($size,0)." ".$bytes[$i];
}
}
// example
echo file_size("example.txt", "myFolder");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment