Back to all posts

Base64 Encoding and Decoding


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:

  1. Grouping: The data is divided into 3-byte chunks.  
  2. Conversion to Binary: Each byte is converted to an 8-bit binary representation.  
  3. Concatenation: The binary values of the three bytes are concatenated into a 24-bit string.
  4. Grouping into 6-bit chunks: The 24-bit string is divided into four 6-bit chunks.  
  5. Conversion to Decimal: Each 6-bit chunk is converted to a decimal number.
  6. Base64 Mapping: The decimal numbers are mapped to the Base64 alphabet (A-Z, a-z, 0-9, +, /).
  7. 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:

  1. Padding Removal: Remove any padding characters (‘=’).
  2. Base64 to Decimal: Convert Base64 characters to their corresponding decimal values.
  3. Grouping into 6-bit chunks: Group the decimal values into 6-bit chunks.
  4. Conversion to Binary: Convert each 6-bit chunk to an 8-bit binary value.
  5. Grouping into 8-bit bytes: Group the binary values into 8-bit bytes.  
  6. 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!