Skip to content
← Back to Functions
Code

Human File Size Formatter

Formats byte counts with consistent units and decimal precision.

Function signature

ogFormatHumanFileSize(bytes, precision = 2, unit_system = 'binary')

Categories

  • Forms and Validation

Parameters

bytesFile size in bytes.precisionNumber of decimal places.unit_systemUnit system, either binary or decimal.

Return value

Short public-safe status message.

  • label
  • value
  • unit
  • bytes

Compatibility

Existing function name and call order preserved; metadata signature corrected to source.

Minimum PHP version: 7.4

Security notes

Validate request method, identity, permissions, and caller-owned allowlists before use; keep secrets and internal paths out of public output.

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Formats byte counts with consistent units and decimal precision.
 *
 * Primary use case: Admin file tools and upload reports.
 * Typical inputs: bytes, precision, unit system.
 * Typical output: display string.
 *
 * Implementation note: Use integers for bytes; do not parse untrusted size strings here.
 *
 * @param int $bytes File size in bytes.
 * @param int $precision Number of decimal places.
 * @param string $unit_system Unit system, either binary or decimal.
 * @return array Structured file-size display result.
 */
function ogFormatHumanFileSize($bytes, $precision = 2, $unit_system = 'binary') {
	$result = array(
		'success' => false,
		'message' => '',
		'data' => array()
	);

	$bytes = (int)$bytes;
	$precision = (int)$precision;
	$unit_system = strtolower(trim((string)$unit_system));

	if ($bytes < 0) {
		$result['message'] = 'Byte count cannot be negative.';
		return $result;
	}
	if ($precision < 0) {
		$precision = 0;
	}
	if ($precision > 6) {
		$precision = 6;
	}

	$base = 1024;
	$units = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB');
	if ($unit_system == 'decimal') {
		$base = 1000;
		$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
	}

	$value = (float)$bytes;
	$unit_index = 0;
	while ($value >= $base && $unit_index < count($units) - 1) {
		$value = $value / $base;
		$unit_index++;
	}

	$label = number_format($value, $precision, '.', '') . ' ' . $units[$unit_index];
	if ($unit_index == 0) {
		$label = (string)$bytes . ' B';
	}

	$result['success'] = true;
	$result['message'] = 'File size formatted.';
	$result['data'] = array(
		'label' => $label,
		'value' => $value,
		'unit' => $units[$unit_index],
		'bytes' => $bytes
	);

	return $result;
}