PHP Reference ยท String Functions
PHP base64_encode() and base64_decode() functions
Reference for PHP base64_encode() and base64_decode(): encode bytes as text, strict mode, URL-safe variants, size overhead and why Base64 is not encryption.
base64_encode() turns any sequence of bytes into text that uses only letters, digits, +, / and the padding character =. base64_decode() reverses it. Base64 exists so that binary data can travel through channels that only handle text: email attachments, JSON fields, data URIs, HTTP headers and configuration files.
The encoded text is about 33% larger than the input: every 3 bytes become 4 characters. Base64 is an encoding, not encryption: anyone can decode it, so it hides nothing.
<?php echo base64_encode("Hello"); // SGVsbG8= echo base64_decode("SGVsbG8="); // Hello
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
base64_encode(string $string): string base64_decode(string $string, bool $strict = false): string|false
| Name | Description |
|---|---|
$string |
The data to encode, or the Base64 text to decode. |
$strict |
If true, base64_decode() returns false when the input contains a character outside the Base64 alphabet (whitespace is still tolerated). If false (the default), such characters are silently skipped. |
Return value: base64_encode() returns the encoded string. base64_decode() returns the decoded bytes, or false on failure (only detected in strict mode, or when the structure is invalid).
Usage notes
- Always pass
truefor untrusted input. Loose mode ignores junk, so malformed data may decode to something unexpected without any signal. - The result can be binary. Decoded data is a byte string; do not print it as text unless you know it is text.
- Padding. Output length is always a multiple of 4, filled with
=. PHP accepts input without the padding. - URL-safe variant. The standard alphabet contains
+and/which have meaning in URLs. PHP has no built-in function for the URL-safe alphabet; use thestrtr()pattern shown above (this is what JWTs use). - Line breaks. MIME wants lines of 76 characters; add them with
chunk_split(). - Not encryption or hashing. Never use Base64 to "protect" a password or a secret. See the cryptography lesson for the right tools.
- Size. Large uploads encoded in memory use roughly 2.3 times the file size in RAM. Stream large files with the
convert.base64-encodestream filter instead. - Hex alternative.
bin2hex()is longer (2 characters per byte) but simpler and case-insensitive.