What is Base64?
Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format. It’s designed to make binary data safe to transport through mediums that only handle text.
How it Works:
Encoding:
- Grouping: The data is divided into 3-byte chunks.
- Conversion to Binary: Each byte is converted to an 8-bit binary representation.
- Concatenation: The binary values of the three bytes are concatenated into a 24-bit string.
- Grouping into 6-bit chunks: The 24-bit string is divided into four 6-bit chunks.
- Conversion to Decimal: Each 6-bit chunk is converted to a decimal number.
- Base64 Mapping: The decimal numbers are mapped to the Base64 alphabet (A-Z, a-z, 0-9, +, /).
- Padding: If the number of bytes is not a multiple of 3, padding is added with ‘=’ characters.
Decoding:
The process is essentially the reverse of encoding:
- Padding Removal: Remove any padding characters (‘=’).
- Base64 to Decimal: Convert Base64 characters to their corresponding decimal values.
- Grouping into 6-bit chunks: Group the decimal values into 6-bit chunks.
- Conversion to Binary: Convert each 6-bit chunk to an 8-bit binary value.
- Grouping into 8-bit bytes: Group the binary values into 8-bit bytes.
- Conversion to Characters: Convert the binary bytes back to their original characters.
Why Use Base64?
- Transporting Binary Data: It allows binary data to be safely sent through text-based channels like email or HTTP.
- Data Storage: It can be used to store binary data in text-based formats like JSON or XML.
- Image Embedding: It’s commonly used to embed images in HTML using the data:
$data = "Hello, world!";
$encoded = base64_encode($data);
echo $encoded; // Output: SGVsbG8sIHdvcmxkIQ==
$decoded = base64_decode($encoded);
echo $decoded; // Output: Hello, world!