PHPackages                             s9e/bencode - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. s9e/bencode

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

s9e/bencode
===========

Fast and efficient bencode decoder/encoder, designed to handle malformed and malicious input gracefully.

2.3.2(2y ago)1068MITPHPPHP &gt;=8.1

Since May 20Pushed 2y ago1 watchersCompare

[ Source](https://github.com/s9e/Bencode)[ Packagist](https://packagist.org/packages/s9e/bencode)[ Docs](https://github.com/s9e/Bencode/)[ RSS](/packages/s9e-bencode/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (3)Versions (28)Used By (0)

s9e\\Bencode is a clean and efficient [Bencode](http://en.wikipedia.org/wiki/Bencode) encoder/decoder. It is designed to handle malformed and malicious input gracefully.

[![Build Status](https://camo.githubusercontent.com/884e794cc7c872a5194c1b16a651df8c2cd4a4eba8c4f6d7a6b2e7fe496845da/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f7339652f42656e636f64652f6261646765732f6275696c642e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/s9e/Bencode/build-status/master)[![Code Coverage](https://camo.githubusercontent.com/ff501aab72f6c9ef15d2827bc49ca14df67af0f8330717ddd53c22a5adb1e4d3/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f7339652f42656e636f64652f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/s9e/Bencode/?branch=master)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/83c4c98f0a87cd5a444f897208001357b978b1845145b01bd63f04fd6d96fb36/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f7339652f42656e636f64652f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/s9e/Bencode/?branch=master)

### Installation

[](#installation)

```
composer require s9e/bencode
```

### Usage

[](#usage)

#### Decode a bencoded string

[](#decode-a-bencoded-string)

```
use s9e\Bencode\Bencode;
print_r(Bencode::decode('d3:bar4:spam3:fooi42ee'));
```

```
ArrayObject Object
(
    [storage:ArrayObject:private] => Array
        (
            [bar] => spam
            [foo] => 42
        )

)

```

#### Encode a PHP value

[](#encode-a-php-value)

```
use s9e\Bencode\Bencode;
print_r(Bencode::encode(['foo' => 42, 'bar' => 'spam']));
```

```
d3:bar4:spam3:fooi42ee

```

Supported types are as follow:

- `array`, `int`, and `string` values are encoded natively.
- `float` values that can be losslessly converted to integers are coerced to `int`.
- `bool` values are coerced to `int`.
- An object that implements `s9e\Bencode\BencodeSerializable` is encoded as the value returned by its `bencodeSerialize()` method.
- The properties of an `stdClass` object are encoded in a dictionary.
- An instance of `ArrayObject` is treated as an array.

```
use s9e\Bencode\Bencode;
use s9e\Bencode\BencodeSerializable;

$bencodable = new class implements BencodeSerializable
{
	public function bencodeSerialize(): array|int|string
	{
		return 42;
	}
};

print_r(Bencode::encode($bencodable));
```

```
i42e

```

#### Handle exceptions

[](#handle-exceptions)

```
try
{
	s9e\Bencode\Bencode::decode('i123x');
}
catch (s9e\Bencode\Exceptions\DecodingException $e)
{
	var_dump($e->getMessage(), $e->getOffset());
}
```

```
string(29) "Illegal character at offset 4"
int(4)

```

```
try
{
	s9e\Bencode\Bencode::encode(2.5);
}
catch (s9e\Bencode\Exceptions\EncodingException $e)
{
	var_dump($e->getMessage(), $e->getValue());
}
```

```
string(17) "Unsupported value"
float(2.5)

```

#### Salvage non-compliant input

[](#salvage-non-compliant-input)

By default, the decoder rejects non-compliant input with a `ComplianceError` exception, which is a subtype of `DecodingException`. If you have to handle input produced by a non-compliant encoder, the `decodeNonCompliant` method may be able to salvage it by replacing illegal values as follow:

- Unordered dictionaries are automatically sorted.
- Duplicate entries in dictionaries overwrite prior entries.
- Integers used as dictionary keys are converted to strings.
- Leading `0`s are removed from integers.
- Negative zero is converted to `0`.
- Trailing junk at the end of the input is ignored.

In the following example, we try to load an invalid dictionary normally and upon failure, we retry using the non-compliant decoder.

```
use s9e\Bencode\Bencode;

$input = 'd3:fooi42e3:bar4:spame';
try
{
	$value = Bencode::decode($input);
}
catch (s9e\Bencode\Exceptions\ComplianceError $e)
{
	echo 'Failed: ', $e->getMessage(), "\nRetry with non-compliant decoder:\n";

	$value = Bencode::decodeNonCompliant($input);
	print_r($value);
}
```

```
Failed: Out of order dictionary entry 'bar' at offset 10
Retry with non-compliant decoder:
ArrayObject Object
(
    [storage:ArrayObject:private] => Array
        (
            [bar] => spam
            [foo] => 42
        )

)

```

### Implementation details

[](#implementation-details)

- Rejects invalid bencoded data with meaningful exception messages.
- Uses [ArrayObject](https://www.php.net/manual/en/class.arrayobject.php) instances to represent dictionaries. Dictionaries can be created and read using either the array notation or the object notation.
- Integers are limited in range from `PHP_INT_MIN` to `PHP_INT_MAX`.
- The encoder accepts booleans but converts them to integers.
- The encoder accepts floats that are equal to their integer value.

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity16

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity82

Battle-tested with a long release history

 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 ~104 days

Recently: every ~79 days

Total

25

Last Release

769d ago

Major Versions

1.3.0 → 2.0.02020-09-25

PHP version history (5 changes)1.0.0PHP &gt;=5.5

1.2.0PHP &gt;=7.2

2.0.0PHP &gt;=7.4

2.0.1PHP &gt;=8.0

2.2.3PHP &gt;=8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/06ce60f935a636cbb13d7ca4733fa28c9a2c9d500834c6481f86e05fd4a55e86?d=identicon)[s9e](/maintainers/s9e)

---

Top Contributors

[![JoshyPHP](https://avatars.githubusercontent.com/u/317712?v=4)](https://github.com/JoshyPHP "JoshyPHP (181 commits)")

---

Tags

bencodebencodingbittorrenttorrentbencodebittorrent

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/s9e-bencode/health.svg)

```
[![Health](https://phpackages.com/badges/s9e-bencode/health.svg)](https://phpackages.com/packages/s9e-bencode)
```

###  Alternatives

[rhilip/bencode

A pure and simple PHP library for encoding and decoding Bencode data

4024.1k2](/packages/rhilip-bencode)[christeredvartsen/php-bittorrent

A set of components that can be used to interact with torrent files (read+write) and classes that can encode/decode to/from the BitTorrent format.

11120.1k2](/packages/christeredvartsen-php-bittorrent)[kleiram/transmission-php

PHP Transmission client

18416.9k1](/packages/kleiram-transmission-php)[arokettu/bencode

BitTorrent's Bencode encoder/decoder

2615.6k7](/packages/arokettu-bencode)[arokettu/torrent-file

A class to work with torrent files

2413.9k3](/packages/arokettu-torrent-file)

PHPackages © 2026

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