Base64 Encoder and Decoder in PHP — Code Examples
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
// 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!");- 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).
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 JavaScript / Node.js
In browsers use btoa() and atob(). In Node.js use Buffer. For Unicode safety in the browser, encode via TextEncoder first.
Base64 Encoder and Decoder in Python
Python's standard library includes the base64 module. Use b64encode and b64decode for standard Base64, and urlsafe_b64encode for URL-safe variants.
Base64 Encoder and Decoder in Go
Go's encoding/base64 package provides StdEncoding for standard Base64 and URLEncoding for the URL-safe variant.
Base64 Encoder and Decoder in Java
Java 8+ includes java.util.Base64. Use getEncoder() for standard Base64 and getUrlEncoder() for URL-safe encoding.
Base64 Encoder and Decoder in Ruby
Ruby's standard library includes the base64 module. Use strict_encode64 and strict_decode64 for standard Base64 without line-break insertion.
Base64 Encoder and Decoder in Rust
Rust uses the base64 crate. Use general_purpose::STANDARD for standard Base64 and URL_SAFE_NO_PAD for JWT and URL contexts.
Base64 Encoder and Decoder in C# / .NET
C# provides Convert.ToBase64String and Convert.FromBase64String in the BCL. For URL-safe Base64, replace non-URL-safe characters after encoding.