Bytes and binary data

suggest change

PHP has no separate "bytes" or "buffer" type. A PHP string is a sequence of bytes with a length, and it can hold any byte value, including \0. The same type stores UTF-8 text, the contents of a JPEG file, a SHA-256 digest or a network packet.

This article covers how to look at and build raw bytes, how to convert integers and floats to and from binary with pack() and unpack(), how to read binary files, and the mistakes people make most often when they treat binary data as text.

Strings are byte arrays

strlen() counts bytes, not characters. $s[$i] returns a one-byte string, and ord() turns that byte into an integer from 0 to 255:

<?php
$s = "héllo";

var_dump(strlen($s));     // bytes
var_dump(mb_strlen($s));  // characters (UTF-8)
echo bin2hex($s), "\n";
echo ord($s[1]), " ", ord($s[2]), "\n"; // 'é' is 2 bytes in UTF-8

Output:

int(6)
int(5)
68c3a96c6c6f
195 169

Nearly all of PHP's standard string functions (strlen, substr, strpos, str_replace, strrev, str_pad, explode, fread, fwrite, ...) are binary-safe: they work on bytes and treat \0 as an ordinary byte, so you can use them directly on binary data. The mb_* functions are the ones that interpret bytes as characters. For more on text encodings see Unicode Support in PHP.

Writing byte literals

Inside double-quoted strings you can write any byte with a hex escape \xHH or an octal escape \NNN, and any Unicode code point (encoded as UTF-8) with \u{...}:

<?php
$pngSignature = "\x89PNG\r\n\x1a\n";
var_dump(strlen($pngSignature));
echo bin2hex($pngSignature), "\n";

$withNul = "a\0b";
var_dump(strlen($withNul), $withNul === "a\x00b");

// \u{...} produces the UTF-8 bytes of the code point
var_dump("\u{1F600}" === "\xF0\x9F\x98\x80");

// chr() builds one byte from an integer 0..255
echo chr(72), chr(0x69), "\n";

Output:

int(8)
89504e470d0a1a0a
int(3)
bool(true)
bool(true)
Hi

Single-quoted strings do not process escapes: '\x00' is four characters, not one byte.

In PHP 8.5, chr() with a value outside 0..255 and ord() with a string that isn't exactly one byte long are deprecated. Use chr($n & 0xFF) if you really mean "wrap around", and always pass a single byte (ord($s[$i])) to ord().

Looking at bytes: hex, binary, hexdump

Raw bytes don't display well, so convert them before printing. bin2hex() and hex2bin() convert between bytes and lowercase hex. sprintf('%08b') shows the bits of one byte:

<?php
echo bin2hex("Hi!"), "\n";
var_dump(hex2bin("cafe") === "\xCA\xFE");

// space-separated hex, one pair per byte
echo implode(' ', str_split(bin2hex("Hi!"), 2)), "\n";

// bits of a byte
printf("%08b\n", ord("A"));

// hex2bin() rejects odd-length or non-hex input
var_dump(@hex2bin("abc"));

Output:

486921
bool(true)
48 69 21
01000001
bool(false)

For anything longer than a few bytes, a hexdump in the style of xxd / hexdump -C is easier to read:

<?php
function hexdump(string $data): void
{
    foreach (str_split($data, 16) as $i => $chunk) {
        $hex = implode(' ', str_split(bin2hex($chunk), 2));
        $ascii = preg_replace('/[^\x20-\x7E]/', '.', $chunk);
        printf("%08x  %-47s  |%s|\n", $i * 16, $hex, $ascii);
    }
}

hexdump("\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR" . "Hello, binary world!");

Output:

00000000  89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52  |.PNG........IHDR|
00000010  48 65 6c 6c 6f 2c 20 62 69 6e 61 72 79 20 77 6f  |Hello, binary wo|
00000020  72 6c 64 21                                      |rld!|

Never var_dump() or echo binary data directly: \0 and control bytes are printed raw and can garble the terminal or be invisible.

pack() and unpack()

pack(string $format, mixed ...$values): string converts values into a binary string. unpack(string $format, string $data, int $offset = 0): array|false does the reverse. The format is a list of codes, each optionally followed by a repeat count or * (all remaining).

The codes you will use most:

Code Meaning Size
C / c unsigned / signed char 1
n / v unsigned 16-bit, big / little endian 2
N / V unsigned 32-bit, big / little endian 4
J / P unsigned 64-bit, big / little endian 8
S, L, Q unsigned 16/32/64-bit, machine byte order 2/4/8
s, l, q signed 16/32/64-bit, machine byte order 2/4/8
G / g float32, big / little endian 4
E / e float64, big / little endian 8
a / A / Z string padded with NUL / space / NUL-terminated count
H / h hex string, high / low nibble first count/2
x NUL byte (pack) / skip one byte (unpack) 1

Network protocols and most file formats specify a byte order, so prefer the explicit-endian codes (n, N, J, v, V, P, E, e, G, g) over the machine-order ones.

<?php
echo bin2hex(pack('n', 0x1234)), "\n";       // big endian 16-bit
echo bin2hex(pack('v', 0x1234)), "\n";       // little endian 16-bit
echo bin2hex(pack('N', 0x12345678)), "\n";   // big endian 32-bit
echo bin2hex(pack('V', 0x12345678)), "\n";   // little endian 32-bit
echo bin2hex(pack('J', 1)), "\n";            // big endian 64-bit
echo bin2hex(pack('E', 1.5)), "\n";          // float64 big endian
echo bin2hex(pack('g', 1.5)), "\n";          // float32 little endian

// several values at once
echo bin2hex(pack('CnN', 1, 2, 3)), "\n";

Output:

1234
3412
12345678
78563412
0000000000000001
3ff8000000000000
0000c03f
01000200000003

Unpacking with names

Without names, unpack() returns an array indexed from 1. Give each code a name (separated by /) to get an associative array:

<?php
$header = "\x00\x02\x00\x00\x00\x10DATA";

print_r(unpack('C*', "Hi!"));
print_r(unpack('nversion/Nlength/a4tag', $header));

// a repeat count with a name produces name1, name2, ...
print_r(unpack('C2byte/nword', "\x01\x02\x00\x03"));

Output:

Array
(
    [1] => 72
    [2] => 105
    [3] => 33
)
Array
(
    [version] => 2
    [length] => 16
    [tag] => DATA
)
Array
(
    [byte1] => 1
    [byte2] => 2
    [word] => 3
)

The third argument of unpack() is a byte offset, which saves a substr() call when a field is in the middle of a buffer:

<?php
$buf = "XXXX\x00\x00\x01\x00";
print_r(unpack('Nlen', $buf, 4));

Output:

Array
(
    [len] => 256
)

If the data is too short, unpack() emits a warning and returns false. Check the length yourself before unpacking untrusted input, so you can throw a meaningful exception instead.

Strings and hex in pack formats

a, A and Z pack fixed-width string fields. On unpack, a keeps the padding, A strips trailing whitespace and NULs, and Z stops at the first NUL:

<?php
echo bin2hex(pack('a5', 'ab')), "\n";
echo bin2hex(pack('A5', 'ab')), "\n";
echo bin2hex(pack('Z5', 'ab')), "\n";

$r = unpack('a5x/A5y/Z5z', "ab\0\0\0ab   ab\0\0\0");
echo bin2hex($r['x']), " ", var_export($r['y'], true), " ", var_export($r['z'], true), "\n";

// H* is another way to convert between hex and bytes
echo bin2hex(pack('H*', 'cafe')), " ", unpack('H*', "\xCA\xFE")[1], "\n";

Output:

6162000000
6162202020
6162000000
6162000000 'ab' 'ab'
cafe cafe

Signed and unsigned integers

PHP integers are signed 64-bit (on all common platforms, PHP_INT_SIZE is 8). This has two consequences when reading binary data.

First, n, v, N and V always unpack as unsigned. There are no explicit-endian signed codes, so convert by hand (two's complement):

<?php
$u = unpack('n', "\xFF\xFE")[1];
var_dump($u);

function toSigned16(int $u): int { return $u >= 0x8000 ? $u - 0x10000 : $u; }
function toSigned32(int $u): int { return $u >= 0x80000000 ? $u - 0x100000000 : $u; }

var_dump(toSigned16($u));
var_dump(toSigned32(unpack('N', "\xFF\xFF\xFF\xFB")[1]));

// one byte: c is signed, C is unsigned
var_dump(unpack('c', "\xFF")[1], unpack('C', "\xFF")[1]);

Output:

int(65534)
int(-2)
int(-5)
int(-1)
int(255)

Second, an unsigned 64-bit value above PHP_INT_MAX doesn't fit in a PHP int, so J, P and Q return it as a negative number. Use sprintf('%u') to print it, or the BCMath / GMP extensions to do arithmetic on it (see Using bcmath to read and write a binary long on a 32-bit system):

<?php
$max = unpack('J', "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF")[1];
var_dump($max);
var_dump(sprintf('%u', $max));

Output:

int(-1)
string(20) "18446744073709551615"

Bit manipulation

Use ord() to get a byte as an integer, the bitwise operators to work on it, and chr() to turn it back into a byte:

<?php
const FLAG_READ  = 0b0001;
const FLAG_WRITE = 0b0010;
const FLAG_EXEC  = 0b0100;

$byte = ord("\x05");                       // 0b0101: READ | EXEC
var_dump(($byte & FLAG_READ) !== 0);       // test a bit
var_dump(($byte & FLAG_WRITE) !== 0);

$byte |= FLAG_WRITE;                       // set a bit
$byte &= ~FLAG_EXEC;                       // clear a bit
printf("%08b %s\n", $byte, bin2hex(chr($byte)));

$b = 0xA7;
printf("high nibble %X, low nibble %X\n", $b >> 4, $b & 0x0F);

Output:

bool(true)
bool(false)
00000011 03
high nibble A, low nibble 7

When you implement algorithms written for 32-bit unsigned integers (checksums, hashes, PRNGs), mask results with & 0xFFFFFFFF after every operation that can overflow 32 bits, because PHP's 64-bit integers won't wrap for you:

<?php
var_dump((0xFFFFFFFF + 1) & 0xFFFFFFFF);
var_dump((0x7FFFFFFF << 1) & 0xFFFFFFFF);

function rotl32(int $x, int $n): int
{
    return (($x << $n) | ($x >> (32 - $n))) & 0xFFFFFFFF;
}
printf("%08x\n", rotl32(0x80000001, 1));

Output:

int(0)
int(4294967294)
00000003

The bitwise operators also work directly on strings, byte by byte. The result is as long as the shorter operand:

<?php
$key = random_bytes(6);
$encrypted = "secret" ^ $key;               // XOR each byte
var_dump(($encrypted ^ $key) === "secret");

echo bin2hex("abc" ^ "a"), "\n";           // only 1 byte long

Output:

bool(true)
00

Don't confuse this with real encryption; see Cryptography.

Example: variable-length integers

Many formats (Protocol Buffers, WebAssembly, Git packfiles) store integers as LEB128 varints: 7 bits per byte, with the high bit set on every byte except the last. It is a good exercise in combining ord(), chr() and shifts:

<?php
declare(strict_types=1);

function varintEncode(int $n): string
{
    if ($n < 0) {
        throw new InvalidArgumentException('Only non-negative values are supported');
    }
    $out = '';
    do {
        $byte = $n & 0x7F;
        $n >>= 7;
        if ($n !== 0) {
            $byte |= 0x80; // more bytes follow
        }
        $out .= chr($byte);
    } while ($n !== 0);
    return $out;
}

function varintDecode(string $buf, int &$offset): int
{
    $result = 0;
    $shift = 0;
    while (true) {
        if ($offset >= strlen($buf)) {
            throw new RuntimeException('Truncated varint');
        }
        $byte = ord($buf[$offset++]);
        $result |= ($byte & 0x7F) << $shift;
        if (($byte & 0x80) === 0) {
            return $result;
        }
        $shift += 7;
        if ($shift > 63) {
            throw new RuntimeException('Varint too long');
        }
    }
}

foreach ([1, 127, 128, 300, 1_000_000] as $n) {
    echo $n, " => ", bin2hex(varintEncode($n)), "\n";
}

$buf = varintEncode(300) . varintEncode(5);
$offset = 0;
var_dump(varintDecode($buf, $offset), varintDecode($buf, $offset), $offset);

Output:

1 => 01
127 => 7f
128 => 8001
300 => ac02
1000000 => c0843d
int(300)
int(5)
int(3)

Reading and writing binary files

Open files in binary mode ('rb', 'wb', 'w+b'). On Linux and macOS the b makes no difference, but on Windows text mode can translate line endings, which corrupts binary data. file_get_contents() and file_put_contents() are always binary-safe. See File handling for the general file API.

This example reads the width and height of a PNG from its header. It builds a tiny valid PNG first, which also shows pack() in the write direction and crc32() for checksums:

<?php
declare(strict_types=1);

function pngSize(string $path): array
{
    $fp = fopen($path, 'rb');
    if ($fp === false) {
        throw new RuntimeException("Cannot open $path");
    }
    try {
        $head = fread($fp, 24);
    } finally {
        fclose($fp);
    }
    if ($head === false || strlen($head) < 24 || !str_starts_with($head, "\x89PNG\r\n\x1a\n")) {
        throw new RuntimeException("$path is not a PNG file");
    }
    // after the 8-byte signature: chunk length, chunk type "IHDR", width, height
    $ihdr = unpack('Nlength/a4type/Nwidth/Nheight', $head, 8);
    if ($ihdr['type'] !== 'IHDR') {
        throw new RuntimeException('First chunk is not IHDR');
    }
    return [$ihdr['width'], $ihdr['height']];
}

function pngChunk(string $type, string $data): string
{
    return pack('N', strlen($data)) . $type . $data . pack('N', crc32($type . $data));
}

// 3x2 pixels, 8-bit RGB; each row starts with a filter-type byte
$pixels = str_repeat("\x00" . str_repeat("\xFF\x00\x00", 3), 2);
$png = "\x89PNG\r\n\x1a\n"
    . pngChunk('IHDR', pack('NNCCCCC', 3, 2, 8, 2, 0, 0, 0))
    . pngChunk('IDAT', gzcompress($pixels))
    . pngChunk('IEND', '');

$path = sys_get_temp_dir() . '/tiny.png';
file_put_contents($path, $png);

[$w, $h] = pngSize($path);
echo "{$w}x{$h}, ", filesize($path), " bytes\n";
echo getimagesize($path)[3], "\n"; // PHP's own parser agrees
unlink($path);

Output:

3x2, 73 bytes
width="3" height="2"

A record format with fread() and fwrite()

fread($fp, $n) may return fewer than $n bytes, especially on sockets and pipes, so loop until you have them all. This example stores records as a big-endian uint32 id, a float64 price, and a length-prefixed name. It uses the in-memory stream php://memory (see Streams), but the code is the same for a real file or socket:

<?php
declare(strict_types=1);

function writeRecord($fp, int $id, float $price, string $name): void
{
    fwrite($fp, pack('NEn', $id, $price, strlen($name)) . $name);
}

function readExactly($fp, int $n): string
{
    $buf = '';
    while (strlen($buf) < $n) {
        $chunk = fread($fp, $n - strlen($buf));
        if ($chunk === false || $chunk === '') {
            throw new RuntimeException("Unexpected end of data: wanted $n bytes, got " . strlen($buf));
        }
        $buf .= $chunk;
    }
    return $buf;
}

function readRecord($fp): ?array
{
    $header = fread($fp, 14); // 4 + 8 + 2 bytes
    if ($header === false || $header === '') {
        return null; // clean end of data
    }
    if (strlen($header) < 14) {
        $header .= readExactly($fp, 14 - strlen($header));
    }
    $rec = unpack('Nid/Eprice/nlen', $header);
    $rec['name'] = readExactly($fp, $rec['len']);
    unset($rec['len']);
    return $rec;
}

$fp = fopen('php://memory', 'w+b');
writeRecord($fp, 1, 9.99, 'Coffee');
writeRecord($fp, 2, 3.5, 'Bagel');
writeRecord($fp, 3, 12.0, 'Croissant €');
echo "size: ", ftell($fp), " bytes\n";

rewind($fp);
while (($rec = readRecord($fp)) !== null) {
    printf("#%d %-14s %6.2f\n", $rec['id'], $rec['name'], $rec['price']);
}
fclose($fp);

Output:

size: 66 bytes
#1 Coffee           9.99
#2 Bagel            3.50
#3 Croissant €   12.00

Note the misaligned last line. The name length prefix correctly counts bytes (€ is 3 bytes in UTF-8), but printf('%-14s') also pads by bytes, not characters. For display, pad with mb_str_pad() (PHP 8.3+) instead.

Base64 and hex for text channels

JSON, URLs, HTTP headers and databases with text columns can't carry arbitrary bytes. Encode binary data before putting it there:

<?php
$bytes = "\xFB\xFF\xFE";

echo bin2hex($bytes), "\n";            // 2 chars per byte
echo base64_encode($bytes), "\n";      // ~1.33 chars per byte

// base64url (used in JWT and URLs): no + / or = padding
$b64url = rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
echo $b64url, "\n";
var_dump(base64_decode(strtr($b64url, '-_', '+/')) === $bytes);

// strict mode returns false for invalid input instead of skipping characters
var_dump(base64_decode('not base64!', true));

// json_encode() requires valid UTF-8
var_dump(json_encode(["data" => $bytes]));
echo json_encode(["data" => base64_encode($bytes)]), "\n";

Output:

fbfffe
+//+
-__-
bool(true)
bool(false)
bool(false)
{"data":"+\/\/+"}

base64_decode() accepts input without = padding, which is why the base64url decode above works without re-adding it.

Hashes, random bytes and comparison

Many functions return either hex text or raw bytes. Raw output is half the size and is what you need for further binary processing (HMAC keys, signatures, concatenating digests):

<?php
$hex = hash('sha256', 'hello');            // 64 hex characters
$raw = hash('sha256', 'hello', true);      // 32 raw bytes
var_dump(strlen($hex), strlen($raw), bin2hex($raw) === $hex);

echo hash('crc32b', 'hello'), " ", dechex(crc32('hello')), "\n";

$token = random_bytes(16);                 // cryptographically secure
echo strlen($token), " bytes -> ", strlen(bin2hex($token)), " hex chars\n";

// compare secrets in constant time
var_dump(hash_equals($raw, hash('sha256', 'hello', true)));

Output:

int(64)
int(32)
bool(true)
3610a686 3610a686
16 bytes -> 32 hex chars
bool(true)

Always compare binary data with ===, strcmp() or hash_equals(), never with ==. Loose comparison treats numeric-looking strings as numbers:

<?php
var_dump("1e3" == "1000");     // both look like numbers
var_dump("1e3" === "1000");
var_dump(strcmp("a\0b", "a\0c")); // binary-safe, NUL is just a byte

Output:

bool(true)
bool(false)
int(-1)

Byte order of the machine

You rarely need it if you use explicit-endian pack codes, but you can detect the native byte order and reverse bytes with strrev():

<?php
$native = pack('S', 1) === "\x01\x00" ? 'little endian' : 'big endian';
echo $native, "\n";

// convert a big-endian 32-bit value to little-endian bytes
echo bin2hex(strrev(pack('N', 0x01020304))), "\n";

Output on x86-64 and ARM64:

little endian
04030201

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents