Skip to content

Instantly share code, notes, and snippets.

@bwente
Created May 19, 2023 23:08
Show Gist options
  • Save bwente/8248fb2742ad4708875e054a3be765df to your computer and use it in GitHub Desktop.
Save bwente/8248fb2742ad4708875e054a3be765df to your computer and use it in GitHub Desktop.
MODX output filter to print out the size of a file
<?php
/**
*
* Example usage: [[*filepath:fmt.fileSize=`mb`]]
*
*/
$units = array(
'gb' => array('size' => 1073741824, 'label' => 'GB'),
'mb' => array('size' => 1048576, 'label' => 'MB'),
'kb' => array('size' => 1024, 'label' => 'KB'),
'b' => array('size' => 0, 'label' => 'bytes')
);
$path = MODX_BASE_PATH . $input;
$size = is_file($path) ? filesize($path) : 0;
$unit = (isset($options) && isset($units[$options])) ? $options : false;
if ($size > 0) {
if ($unit === false) {
// If the unit is not specified, detect it automatically.
foreach ($units as $key => $properties) {
if ($size >= $properties['size']) {
$unit = $key;
break;
}
}
}
if ($unit != 'b') {
$size = $size / $units[$unit]['size'];
}
}
else {
if ($unit === false) {
$unit = 'b';
}
}
return round($size, 2) . ' ' . $units[$unit]['label'];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment