PHP base64_encode() Function

Definition
In PHP, base64_encode() turns data into a plain-text string made only of letters, digits, +, / and =.
It is handy when binary data must travel through text, such as in an email, a JSON file, or a data URI.
Syntax
Call base64_encode() with the values you need. Start with this line.
$encoded = base64_encode($data);
| Call | What it does |
|---|
base64_encode("Hello") | Returns "SGVsbG8=". |
base64_encode("A") | Returns "QQ==". |
The result is about 33% longer than the original data.
Library declarations
base64_encode(string $string): string
Parameters
| Parameter | Description |
|---|
| string | Required. The data to encode. |
Return Value
| Return Value | Description |
|---|
| string | The base64 encoded text. |
PHP Examples
Example 1 — Encode a String
Convert a short text into base64.
<?php
$text = "Hello World";
echo base64_encode($text), PHP_EOL;
How It Works
- Start with a string. Any bytes work, not just text.
- Call base64_encode(). Every 3 bytes become 4 characters.
- Get a safe text string. It uses only letters, digits,
+, / and =. - Print the result. You can decode it later with
base64_decode().
Example 2 — See How Padding Works
The = sign pads the end when the data is not a multiple of 3 bytes.
<?php
echo base64_encode("A"), PHP_EOL;
echo base64_encode("AB"), PHP_EOL;
echo base64_encode("ABC"), PHP_EOL;
How It Works
- Encode 1 byte. It needs two
= signs to fill the last group. - Encode 2 bytes. It needs one
= sign. - Encode 3 bytes. They fit one full group, so there is no padding.
- Remember the rule. Padding only fills the last group of 4 characters.
Frequently Asked Questions
base64_encode() converts data into a base64 text string so it can be sent or stored where only plain text is allowed.
base64_encode(string $string): string. Pass the data to encode and it returns the base64 text.
The = sign is padding. It fills the last group of 4 characters when the input length is not a multiple of 3.
The normal output may contain + and /, which have special meaning in URLs. Replace them with - and _, or run the result through rawurlencode().
No. Base64 is only an encoding, not encryption. Use password_hash() to store passwords.
CODETOFUN NEWS
Stay Ahead in Tech
Get the latest IT news, programming updates, and technology trends directly on your phone.
About the author
Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
8 people found this page helpful