Skip to content

Base64 Encode / Decode — PHP source

Encode text to Base64 or decode it back. UTF-8 safe, runs entirely in your browser, with a shareable link to your exact input.

This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.

<?php
/**
 * base64 — UTF-8 safe Base64 encode/decode.
 *
 * Language: PHP 7.4+ (standard library only).
 * CosmoDev polyglot showcase port of the `base64` tool, ported from
 * src/lib/base64.ts (the canonical TypeScript implementation).
 *
 * PHP strings are raw byte buffers rather than Unicode sequences. As long as
 * the input is UTF-8 (the modern PHP default and true throughout CosmoDev),
 * those bytes ARE the UTF-8 encoding, so base64_encode / base64_decode operate
 * on the correct bytes with no separate "encode to UTF-8" step — the same
 * shortcut Go and Rust enjoy.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

declare(strict_types=1);

/**
 * Encode a Unicode string to standard (padded) Base64.
 *
 * Operates directly on the raw bytes of $str, which are its UTF-8 byte
 * sequence whenever the source string is UTF-8.
 */
function b64encode(string $str): string
{
    return base64_encode($str);
}

/**
 * Decode a standard Base64 string back to the original Unicode text.
 *
 * Embedded whitespace (spaces, tabs, newlines) is stripped first so that
 * line-wrapped Base64 decodes cleanly. Strict mode — the second argument to
 * base64_decode — makes it reject characters outside the alphabet instead of
 * silently dropping them; on rejection we throw a RuntimeException, matching
 * the TypeScript port's "throw on invalid input" contract.
 *
 * @throws \RuntimeException when the input is not valid Base64.
 */
function b64decode(string $b64): string
{
    // Collapse any run of ASCII whitespace before decoding.
    $cleaned = preg_replace('/\s+/', '', $b64);

    // base64_decode($strict = true) returns false for malformed input: an
    // illegal character, or a length that is not a multiple of 4.
    $bytes = base64_decode($cleaned, true);
    if ($bytes === false) {
        throw new RuntimeException('Invalid Base64 input');
    }

    // PHP strings are byte buffers, so the decoded UTF-8 bytes are already the
    // text we want to hand back.
    return $bytes;
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →