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.

Usage:
{$fileSizeInBytes|file_size}

Example:
{assign var=fileSizeInBytes value=10485760}
{$fileSizeInBytes|file_size}

{assign var=fileSizeInBytes value= 768000}
{$fileSizeInBytes|file_size}

{assign var=fileSizeInBytes value=303}
{$fileSizeInBytes|file_size}

Output:
10 MB
750 Kb
303 bytes

<?php
/**
 * 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";
    }
    else
    {
        $output = $bytes . " bytes";
    }

    return $output;
}

/* vim: set expandtab: */

?>

Related articles

 Comments 4 comments

  • yo says:

    Yo this is handy, thanks!

    ReplyReply
  • Johan says:

    Thanx, very useful!

    ReplyReply
  • Paul says:

    This is very usefull, thank you. One mistake though:
    “Kb” should be either “kB” or “KiB”:
    http://en.wikipedia.org/wiki/Kilobyte

    ReplyReply
  • 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.

    ReplyReply

  • Leave a Reply

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