Smarty File Size Modifier

 May, 02 - 2009   4 comments   How To

Here’s a simple Smarty modifier that will format an integer that represents the number of bytes in a file as a human readable string.


{assign var=fileSizeInBytes value=10485760}

{assign var=fileSizeInBytes value= 768000}

{assign var=fileSizeInBytes value=303}

10 MB
750 Kb
303 bytes

 * Smarty plugin
 * @package Smarty
 * @subpackage plugins

 * Smarty file_size modifier plugin
 * Type:     modifier<br>
 * Name:     file_size<br>
 * Purpose:  format file size represented in bytes into a human readable string<br>
 * Input:<br>
 *         - bytes: input bytes integer
 * @author   Rob Ruchte <rob at thirdpartylabs dot com>

 * @param integer
 * @return string
function smarty_modifier_file_size($bytes=0)
    $mb = 1024*1024;

    if ($bytes > $mb)
        $output = sprintf ("%01.2f",$bytes/$mb) . " MB";
    elseif ( $bytes >= 1024 )
        $output = sprintf ("%01.0f",$bytes/1024) . " Kb";
        $output = $bytes . " bytes";

    return $output;

/* vim: set expandtab: */


Related articles

 Comments 4 comments

  • yo says:

    Yo this is handy, thanks!

  • Johan says:

    Thanx, very useful!

  • Paul says:

    This is very usefull, thank you. One mistake though:
    “Kb” should be either “kB” or “KiB”:

  • jon jon says:

    Ambiguity noted, however the only time I’m aware of that people actually talk about kiloBITS is when discussing transfer rates over IP (as modem speeds are typically rated in kilo/mega-BITS per second). I’m pretty sure no one thinks we really mean kilobits when discussing filesize as there’s never any reason to measure it that way. Your real beef should be with ISPs who use the kilo/mega-bit in an effort to psychologically boost their speeds x8.


  • Leave a Reply

    Your email address will not be published. Fields with * are mandatory.