Calculating FileSize in PHP

Calculating FileSize in PHP

The following example illustrates how to read the filesize and convert the number of bytes into KB,MB etc.

Example<?php

<?php// the $file without the path, put the path in the $path-variable (based on the doc. root)

function file_size($file, $path = “”) {

global $DOCUMENT_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) {

return round($size,1).” ”.$bytes[$i];

} else {

return round($size,0).” ”.$bytes[$i];

}

}

// calling file_size function

echo file_size(”sample.txt”, “FolderName”);

?>

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.