PHP Byte Conversion
PHP is a programming language frequently used to create rich, interactive Web applications. PHP code is executed by a Web server and interacts with your users via HTML and Javascript such as AJAX. It may be useful to measure file size using PHP to estimate upload or download times and create meaningful user interaction within your application.
-
File Size
-
For a file resident on the server on which PHP code is executing, file size can be measured by the PHP filesize() function. The file size function returns the size of the file as an integer representing the total number of bytes. However, humans are used to thinking of file sizes in kB, MB and GB, not simply a large number of bytes.
$my_file_size = filesize( $my_file_name);
Number of Bytes
-
Bytes measurements used metric prefixes: kilo, mega, giga, tera. Each step can be in increments of either 1,000 or 1,024, depending on the cited authority. A step size of 1,000 is truer to the metric standard, but a step size of 1,024 is true to the binary roots of computer calculations.
$size_standards = array('bytes', 'kB', 'MB', 'GB', 'TB');
$size_step = 1024; -
Calculation
-
Human-readable file size can be calculated by iteratively dividing by 1,024—or 1,000—until the result is less than the step size.
$calculated_size = $my_file_size;
$reduction_count = 0;
while ($calculated_size > $step_size):
$calculated_size = $calculated_size / $step_size;
$reduction_count++;
endwhile;
Display
-
The result can be displayed using the PHP "print" language construct to display the result at the appropriate location in your PHP application. Note that you must use double quotes for variables in the string to be parsed.
print "The size of $my_file_name is $calculated_size $size_standards[$reduction_count]."
The result will display output such as, "The size of vacation_picture.jpg is 3.403 MB."
-
References
- Photo Credit Jupiterimages/Photos.com/Getty Images