14.2. Obscuring Data with Encoding

Problem

You want to prevent data being viewable as plaintext. For example, you don’t want hidden form data to be revealed simply by someone viewing the source code of a web page.

Solution

Encode the data with base64_encode( ) :

$personal_data = array('code' => 5123, 'blood_type' => 'O');
$info = base64_encode(serialize($personal_data));
print '<input type="hidden" name="info" value="'.$info.'">';
<input type="hidden" name="info"
               value="YToyOntzOjQ6ImNvZGUiO2k6NTEyMztzOjEwOiJibG9vZF90eXBlIjtzOjE6Ik8iO30=">

Decode the data with base64_decode( ) :

$personal_data = unserialize(base64_decode($_REQUEST['info']));
get_transfusion($personal_data['blood_type']);

Discussion

The Base64 algorithm encodes data as a string of letters, numbers, and punctuation marks. This makes it ideal for transforming binary data into a plaintext form and also for obfuscating data.

See Also

Documentation on base64_encode( ) at http://www.php.net/base64-encode and base64_decode( ) at http://www.php.net/base64-decode; the Base64 algorithm is defined in RFC 2045, available at http://www.faqs.org/rfcs/rfc2045.html.

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.