Developer Documentation
PHP
Updated September 19, 2026

Base64 Encoding and Decoding in PHP

Encode and decode Base64 safely, including UTF-8 text and binary data in PHP.

Base64 converts binary data to printable ASCII text. It is useful for transport and embedding, but it is an encoding format, not encryption.

Quick Start#

The following example uses the standard PHP API or a widely used package for this task.

Quick start#

PHP
1<?php2$text = "Hello ToolPorta";3$encoded = base64_encode($text);4$decoded = base64_decode($encoded, true);56if ($decoded === false) {7    throw new RuntimeException("Invalid Base64 input");8}910echo $encoded . PHP_EOL;11echo $decoded . PHP_EOL;

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

URL-safe Base64#

PHP
1<?php2function base64url_encode(string $data): string {3    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');4}56function base64url_decode(string $data): string|false {7    $padded = str_pad($data, strlen($data) + (( - strlen($data) % ) % ), '=');8    return base64_decode(strtr($padded, '-_', '+/'), true);9}

Important Notes#

Use strict decoding (base64_decode($value, true)) when malformed input should be rejected.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement Base64 in other languages: