Base64 Encode and Decode
Encodes a string with base64_encode(), decodes it with strict base64_decode(), and confirms the round trip.
Purpose
Encodes a string with base64_encode(), decodes it with strict base64_decode(), and confirms the round trip.
Snippet details
ContextUtilityLevelProductionCopy-and-paste statusMarked safe after review.Categories
- Forms and Validation
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Base64 Encode and Decode.
*
* Purpose:
* Demonstrates Base64 encoding and strict decoding for transport-safe text,
* while making clear that Base64 is not encryption.
*
* @param string $message Plain message to encode and decode.
* @return array Encoded value, decoded value, and round-trip status.
*/
function ogSnippetBase64EncodeDecode(string $message): array {
if ($message === '') {
return array(
'success' => false,
'encoded' => '',
'decoded' => '',
'round_trip_ok' => false,
'message' => 'A message is required.'
);
}
$encoded = base64_encode($message);
$decoded = base64_decode($encoded, true);
if ($decoded === false) {
return array(
'success' => false,
'encoded' => $encoded,
'decoded' => '',
'round_trip_ok' => false,
'message' => 'Encoded message could not be decoded.'
);
}
return array(
'success' => true,
'encoded' => $encoded,
'decoded' => $decoded,
'round_trip_ok' => $decoded === $message,
'message' => 'Base64 round trip completed.'
);
}
/*
$result = ogSnippetBase64EncodeDecode('Nostromo manifest: specimen container sealed');
print_r($result);
*/