Base64 Encoding in PHP

PHP provides built-in support for base64 encoding/decoding.

<?php

// Here's the string we'll encode/decode.
$data = "abc123!?$*&()'-=@~";

// PHP supports both standard and URL-compatible base64.
// Here's how to encode using the standard encoder.
$sEnc = base64_encode($data);
echo $sEnc . "\n";

// Decoding may return false if the input is not valid base64.
$sDec = base64_decode($sEnc);
echo $sDec . "\n\n";

// This encodes/decodes using a URL-compatible base64 format.
$uEnc = strtr(base64_encode($data), '+/', '-_');
echo $uEnc . "\n";
$uDec = base64_decode(strtr($uEnc, '-_', '+/'));
echo $uDec . "\n";

The string encodes to slightly different values with the standard and URL-safe base64 encoders (trailing + vs -) but they both decode to the original string as desired.

To run the program, save it as base64_encoding.php and use the PHP CLI:

$ php base64_encoding.php
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~

In PHP, base64 encoding and decoding are handled by built-in functions base64_encode() and base64_decode(). For URL-safe encoding, we use the strtr() function to replace + with - and / with _.

Unlike in some languages, PHP’s base64_decode() function automatically handles both standard and URL-safe base64 encoded strings, so we don’t need a separate function for URL-safe decoding.

Remember that base64 encoding is not a form of encryption and should not be used for securing sensitive data. It’s primarily used for encoding binary data to be transmitted over text-based protocols.