Introduction


The example PHP program below shows how to encode and decode a string using the Base64 algorithm. Base64 encoding is used to convert binary data into a text-like format to be transported in environments that handle only text safely. For example, encoding UID's for use in HTTP URL's or to encode encryption keys to make them safely portable through e-mail, display them in HTML pages and use them with copy and paste.

PHP has build-in functions to encode and decode base64, it does not require additional libs or modules.

<?php
# ###################################################################### #
# file:        base64_stringencode.php v1.0                              #
# purpose:     tests encoding/decoding strings with base64               #
# author:      02/23/2009 Frank4DD                                       #
#                                                                        #
# This program encodes and decodes a sample string with base64 format.   #
# ########################################################################

$mysrc = "My bonnie is over the          ";
$myb64 = "";
$mydst = "";

$myb64 = base64_encode($mysrc);
printf("The string\n[%s]\nencodes into base64 as:\n[%s]\n", $mysrc, $myb64);
printf("\n");

$mydst = base64_decode($myb64);
printf("The string\n[%s]\ndecodes from base64 as:\n[%s]\n", $myb64, $mydst);

?>

A test run of the program returns the following output:

fm@susie114:~> php base64_stringencode.php
The string
[My bonnie is over the          ]
encodes into base64 as:
[TXkgYm9ubmllIGlzIG92ZXIgdGhlICAgICAgICAgIA==]

The string
[TXkgYm9ubmllIGlzIG92ZXIgdGhlICAgICAgICAgIA==]
decodes from base64 as:
[My bonnie is over the          ]

Sample Code:

See Also: