DevToolsForYou

Base64 Encoder and Decoder in PHP — Code Examples

Base64 Encoder and Decoder in PHPUse the online tool →

Base64 encoding converts binary or text data into a 64-character ASCII alphabet so it can be safely transmitted over text-only channels. Here is how to encode and decode Base64 in each language using only the standard library.

PHP has built-in base64_encode() and base64_decode() functions. For URL-safe Base64, replace the non-URL-safe characters after encoding.

PHP
<?php

// Encode
$encoded = base64_encode("Hello, world!");
echo $encoded; // SGVsbG8sIHdvcmxkIQ==

// Decode
$decoded = base64_decode("SGVsbG8sIHdvcmxkIQ==");
echo $decoded; // Hello, world!

// URL-safe Base64 (for tokens, JWTs, URLs)
function base64url_encode(string $data): string {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function base64url_decode(string $data): string {
    return base64_decode(strtr($data, '-_', '+/'));
}

echo base64url_encode("Hello, world!");
Notes & gotchas
  • base64_decode() returns false on malformed input — check the return value.
  • PHP has no built-in URL-safe Base64; use the strtr() helper shown above.
  • Pass true as the second argument to base64_decode() for strict mode (rejects invalid characters).
Try it in your browser

Need to base64 encode/decode without writing code? The Base64 Encoder and Decoder runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open Base64 Encode/Decode
Base64 Encoder and Decoder in other languages