PHPackages                             nassiry/filesize-handler - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [File &amp; Storage](/categories/file-storage)
4. /
5. nassiry/filesize-handler

ActiveLibrary[File &amp; Storage](/categories/file-storage)

nassiry/filesize-handler
========================

A PHP package for handling file size with binary, decimal &amp; locale units support.

1.1.0(1y ago)3364MITPHPPHP &gt;=8.0

Since Jan 7Pushed 1y ago1 watchersCompare

[ Source](https://github.com/nassiry/filesize-handler)[ Packagist](https://packagist.org/packages/nassiry/filesize-handler)[ RSS](/packages/nassiry-filesize-handler/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (1)Versions (3)Used By (4)

PHP FileSizeHandler
===================

[](#php-filesizehandler)

[![Packagist Downloads](https://camo.githubusercontent.com/8217ec1381837f7e9e4a583ee3a02be8dbc7c520eabc59a757f00d72f5037820/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6e6173736972792f66696c6573697a652d68616e646c6572)](https://camo.githubusercontent.com/8217ec1381837f7e9e4a583ee3a02be8dbc7c520eabc59a757f00d72f5037820/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6e6173736972792f66696c6573697a652d68616e646c6572)[![Packagist Version](https://camo.githubusercontent.com/145696d545f77d59dcab9c93835a094177f2f59e26d92759738b835ef98820c8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6e6173736972792f66696c6573697a652d68616e646c6572)](https://camo.githubusercontent.com/145696d545f77d59dcab9c93835a094177f2f59e26d92759738b835ef98820c8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6e6173736972792f66696c6573697a652d68616e646c6572)[![PHP](https://camo.githubusercontent.com/29e76b25f44fd19ba3a88f85f00b3ac7329ffd604075db0fbbeda87f6c794491/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253545382e302d626c7565)](https://camo.githubusercontent.com/29e76b25f44fd19ba3a88f85f00b3ac7329ffd604075db0fbbeda87f6c794491/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253545382e302d626c7565)[![License](https://camo.githubusercontent.com/ab2b2485929f85528a16da375bbdfa49420e972bb68e925cfa854cf7bf2fa418/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6e6173736972792f66696c6573697a652d68616e646c6572)](https://camo.githubusercontent.com/ab2b2485929f85528a16da375bbdfa49420e972bb68e925cfa854cf7bf2fa418/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6e6173736972792f66696c6573697a652d68616e646c6572)

The `FileSizeHandler` class is a utility designed to fetch and format file sizes across various file storage systems. It offers cross-platform compatibility with support for both **SI (decimal)** and **IEC (binary)** standards, making it HDD-agnostic and highly flexible.

- **Local Files**
- **Remote Files (HTTP/HTTPS)** (via [Remote File Extension](https://github.com/nassiry/filesize-handler-remote-extension))
- **FTP** (via [FTP Extension](https://github.com/nassiry/filesize-handler-ftp-extension))
- **Amazon S3** (via [S3 Extension](https://github.com/nassiry/filesize-handler-s3-extension))
- **Google Cloud Storage** (via [Google Cloud Extension](https://github.com/nassiry/filesize-handler-google-cloud-extension))
- **Custom Sources** (via user-implemented interfaces)

This package addresses the discrepancies in file size measurement (binary vs decimal units) and provides flexible APIs for developers.

### Features

[](#features)

1. **Supports Local, Remote, and FTP Files:**
    - Easily calculate file sizes from multiple sources.
2. **Binary and Decimal Calculations:**
    - Switch between binary (KiB, MiB, etc.) and decimal (KB, MB, etc.) bases with simple methods.
3. **Fluent Interface:**
    - Intuitive method chaining for base selection and size formatting.
4. **Extensibility:**
    - Ready for integration with cloud storage systems like S3 and Google Cloud.
5. **i18n Support:**
    - Format file size with custom localized units.
    - Dynamically provide translations for units.
6. **Chaining and Echo Support:**
    - Supports method chaining for cleaner code.
    - Directly `echo` the handler instance to get the formatted size.
7. **Custom Source Support**:
    - Implement `FileSourceInterface` and register your custom source.

Table Of Contents
-----------------

[](#table-of-contents)

1. [Why Was This Class Created?](#why-was-this-class-created)
2. [Useful Links](#useful-links)
3. [Requirements](#requirements)
4. [Installation](#installation)
5. [Usage](#usage)
    - [Local File](#local-file)
    - [Extending the Library](#extending-the-library)
6. [Binary vs Decimal Units](#binary-vs-decimal-units)
    - [Switching Units](#switching-units)
    - [Dynamic Locale and Unit Customization](#dynamic-locale-and-unit-customization)
7. [API Reference](#api-reference)
    - [Source Methods](#source-methods)
    - [Configuration Methods](#configuration-methods)
    - [Output Methods](#output-methods)
8. [Extensions](#extensions)
    - [Available Extensions](#available-extensions)
9. [Contributing](#contributing)
10. [License](#license)

### Why Was This Class Created?

[](#why-was-this-class-created)

When working with file sizes, differences in measurement units across systems can cause confusion:

- **Cross-OS Consistency**: File size interpretations vary between operating systems (Windows, Linux, macOS) and hardware (HDD/SSD manufacturers often use decimal, while OS file systems may use binary).
- **Unified Interface**: Simplifies handling file size retrieval from diverse sources.
- **Extensibility**: Easily extend functionality by integrating additional storage systems via a simple, well-defined interface.

#### Useful Links

[](#useful-links)

1. [Wikipedia: Binary Prefixes](https://en.wikipedia.org/wiki/Binary_prefix?utm_source=filesize-handler)
    - Comprehensive explanation of binary (KiB, MiB) vs. decimal (KB, MB) prefixes.
2. [NIST: Prefixes for Binary Multiples](https://physics.nist.gov/cuu/Units/binary.html?utm_source=filesize-handler)
    - Official standards for binary-based units.
3. [IBM: Units of Measurement for Storage Data](https://www.ibm.com/docs/en/storage-insights?topic=overview-units-measurement-storage-data)
    - Insights into storage measurement across platforms.
4. [Google: Byte Units](https://developers.google.com/style/units-of-measure#byte-units)
    - Guidelines for using decimal and binary units consistently.
5. [Metric View: What are binary prefixes?](https://metricviews.uk/2024/02/18/what-are-binary-prefixes/?utm_source=filesize-handler)
    - Provides an overview of binary prefixes and their usage

### Requirements

[](#requirements)

- **PHP**: Version 8.0 or higher
- **PHP Extension** - `ext-intl`: Required

Installation
------------

[](#installation)

The recommended way use Composer to install the package:

```
composer require nassiry/filesize-handler
```

### Usage

[](#usage)

### Local File

[](#local-file)

By default, the library supports fetching file sizes for local files.

```
use Nassiry\FileSizeUtility\FileSizeHandler;

$handler = FileSizeHandler::create()
    ->local('/path/to/file')
    ->binary();

// Get the formatted size
echo $handler->format(); // Example output: "1.23 MiB"

// Or use directly with echo
echo FileSizeHandler::create()
    ->local('/path/to/file')
    ->binary()
    ->format();
```

### Extending the Library

[](#extending-the-library)

To add support for a new file source, implement the `FileSourceInterface`:

```
use Nassiry\FileSizeUtility\Sources\FileSourceInterface;

class CustomCloudSource implements FileSourceInterface
{
    public function __construct(private string $apiKey, private string $filePath) {}

    public function getSizeInBytes(): int
    {
        // Implement API logic to get file size
        return 123456789;
    }
}

$customSource = new CustomCloudSource('api-key', '/path/to/file');

// Once implemented, register your custom source using:
$handler = FileSizeHandler::create()
    ->from($customSource)
    ->binary();

echo $handler->format(); // Example output: "1.23 MiB"
```

> For more information on extending the library, check the [official extensions](#available-extensions) available.

Binary vs Decimal Units
-----------------------

[](#binary-vs-decimal-units)

### Switching Units

[](#switching-units)

```
$handler = FileSizeHandler::create()
    ->local('/path/to/file.txt');

// Default: Binary (1024-based)
echo $handler->format(); // Output: "1.23 MiB"

// Switch to Decimal (1000-based)
echo $handler->decimal()->format(); // Output: "1.30 MB"
```

### Dynamic Locale and Unit Customization

[](#dynamic-locale-and-unit-customization)

```
$customUnits = [
    'binary_units' => ['o', 'Kio', 'Mio', 'Gio', 'Tio', 'Pio', 'Eio', 'Zio', 'Yio'],
    'decimal_units' => ['o', 'Ko', 'Mo', 'Go', 'To', 'Po', 'Eo', 'Zo', 'Yo'],
];

$handler = FileSizeHandler::create('fr_FR', $customUnits)
    ->local('/path/to/file')
    ->binary();

echo $handler->format(1); // Example output: "1,2 Mio"
```

#### Key Points:

[](#key-points)

Two-letter country codes are based on the [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) standard and are used in locale naming conventions.

- **Examples of Supported Locales**: `en_US`, `fr_FR`, `de_DE`.
- **The Default**: units and locale are set to `en_US`

API Reference
-------------

[](#api-reference)

#### `FileSizeHandler::create(string $locale = 'en_US', array $units = [])`

[](#filesizehandlercreatestring-locale--en_us-array-units--)

Initializes a new `FileSizeHandler` instance.

#### Source Methods

[](#source-methods)

- `local(string $filePath): self`
    Creates an instance for a local file.
- `from(FileSourceInterface $source): self`
    Allows integration of a custom file source by implementing the `FileSourceInterface`.

#### Configuration Methods

[](#configuration-methods)

- `binary(): self`
    Switches unit calculation to binary (1024-based).
- `decimal(): self`
    Switches unit calculation to decimal (1000-based).

#### Output Methods

[](#output-methods)

- `bytes(): int`
    Returns the file size in bytes.
- `format(int $precision = 2): string`
    Returns the formatted file size with the specified precision.

### Extensions

[](#extensions)

`FileSizeHandler` is extensible via optional extensions for advanced integrations. These extensions add support for remote and cloud-based file sources. Install the extensions via Composer.

#### Available Extensions:

[](#available-extensions)

ExtensionDescriptionInstallation CommandDocumentation**FTP**Support for FTP file size retrieval.`composer require nassiry/filesize-handler-ftp-extension`[See Full Documentation](https://github.com/nassiry/filesize-handler-ftp-extension)**Amazon S3**Fetch file sizes from Amazon S3 buckets.`composer require nassiry/filesize-handler-s3-extension`[See Full Documentation](https://github.com/nassiry/filesize-handler-s3-extension)**Google Cloud**Retrieve file sizes from Google Cloud Storage.`composer require nassiry/filesize-handler-googlecloud-extension`[See Full Documentation](https://github.com/nassiry/filesize-handler-google-cloud-extension)**Remote**Support for files accessible via HTTP/HTTPS.`composer require nassiry/filesize-handler-remote-extension`[See Full Documentation](https://github.com/nassiry/filesize-handler-remote-extension)### Contributing

[](#contributing)

Feel free to submit issues or pull requests to improve the package. Contributions are welcome!

### Changelog

[](#changelog)

See [CHANGELOG](CHANGELOG.md) for release details.

#### ⚠️ Deprecated Methods

[](#️-deprecated-methods)

As of version 1.1.0, the following methods are deprecated and will be removed in version 2.0.0:

DeprecatedUse Instead`baseBinary()``binary()``baseDecimal()``decimal()``formattedSize()``format()``sizeInBytes()``bytes()`### License

[](#license)

This package is open-source software licensed under the [MIT license](LICENSE).

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance48

Moderate activity, may be stable

Popularity11

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~102 days

Total

2

Last Release

389d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5d313e55474ce48c3b19820c784435215bb56c4497557b603583dcf59ba2270c?d=identicon)[nassiry](/maintainers/nassiry)

---

Top Contributors

[![nassiry](https://avatars.githubusercontent.com/u/105405739?v=4)](https://github.com/nassiry "nassiry (10 commits)")

---

Tags

binary-file-sizebinary-prefixdecimal-file-sizedecimal-prefixfile-size-prefixiec-file-sizephp-amazon-file-sizephp-file-sizephp-ftp-file-sizesi-file-sizefile-sizephp-file-ziephp-size-binaryphp-size-decimal

### Embed Badge

![Health badge](/badges/nassiry-filesize-handler/health.svg)

```
[![Health](https://phpackages.com/badges/nassiry-filesize-handler/health.svg)](https://phpackages.com/packages/nassiry-filesize-handler)
```

###  Alternatives

[humanmade/s3-uploads

WordPress plugin to store uploads on S3

2.1k2.4M9](/packages/humanmade-s3-uploads)[deliciousbrains/wp-amazon-s3-and-cloudfront

Automatically copies media uploads to a storage provider's bucket for delivery. Optionally configure a CDN for even faster delivery.

310213.3k1](/packages/deliciousbrains-wp-amazon-s3-and-cloudfront)[humanmade/network-media-library

Network Media Library provides a central media library that's shared across all sites on the Multisite network.

29644.8k](/packages/humanmade-network-media-library)[humanmade/amf-wordpress

Use another WordPress site as source for your media library.

52175.7k2](/packages/humanmade-amf-wordpress)[fusic/filebinder

Simple file attachment plugin for CakePHP

7230.1k](/packages/fusic-filebinder)[edwardspec/mediawiki-aws-s3

Allows MediaWiki to use Amazon S3 to store uploaded files.

4913.2k](/packages/edwardspec-mediawiki-aws-s3)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
