note 39143 added to function.filesize

From: Date: Sun, 18 Jan 2004 18:39:11 +0000
Subject: note 39143 added to function.filesize
Groups: php.notes 
Request: Send a blank email to php-notes+get-63797@lists.php.net to get a copy of this message
This function converts bytes to a human readable format, by default it scales from bytes to terabytes but you can also supply your own names to localize it to other languages or extend it beyond terabytes. /** * Converts bytes to a human readable string * @param int $bytes Number of bytes * @param int $precision Number of decimal places to include in return string * @param array $names Custom usage strings * @return string formatted string rounded to $precision */ function bytesToHumanReadableUsage($bytes, $precision = 2, $names = '') { if (!is_numeric($bytes) || $bytes < 0) { return false; } for ($level = 0; $bytes >= 1024; $level++) { $bytes /= 1024; } switch ($level) { case 0: $suffix = (isset($names[0])) ? $names[0] : 'Bytes'; break; case 1: $suffix = (isset($names[1])) ? $names[1] : 'KB'; break; case 2: $suffix = (isset($names[2])) ? $names[2] : 'MB'; break; case 3: $suffix = (isset($names[3])) ? $names[3] : 'GB'; break; case 4: $suffix = (isset($names[4])) ? $names[4] : 'TB'; break; default: $suffix = (isset($names[$level])) ? $names[$level] : ''; break; } if (empty($suffix)) { trigger_error('Unable to find suffix for case ' . $level); return false; } return round($bytes, $precision) . ' ' . $suffix; } // example with an existing integer print bytesToHumanReadableUsage('1024'); // example with a local filesystem file print bytesToHumanReadableUsage(filesize('picture.jpg')); ---- Manual Page -- http://www.php.net/manual/en/function.filesize.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+39143 Delete -- http://master.php.net/manage/user-notes.php?action=delete+39143&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+39143&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#63797) next »