PHP Base64 Decode
To convert Base64 to original data, PHP provides the base64_decode
function. In PHP Base64 values are obtained using the base64_encode function. Decoding data is a fairly simple and fast process, but you need to be aware about some pitfalls. Speaking of pitfalls, first of all I mean the necessity to check boolean FALSE
and enable $strict
mode for unknown data.
Usage:
base64_decode($data)
- Strips invalid characters from$data
, then decodes it and returns value asSTRING
base64_decode($data, true)
- Enables$strict
mode and returnsSTRING
if$data
contains only Base64 characters
Arguments:
$data
(required string) - The Base64 value you want to decode$strict
(optional boolean; defaultFALSE
) - SpecifyTRUE
to accept only valid Base64 characters
Return Values:
STRING
- On success, it returns the original data (it can be either text or binary)FALSE
- If a failure occurs (if cannot decode$data
), it returns booleanFALSE
Supported Versions:
- PHP 4
- PHP 5
- PHP 7
Changelog:
- PHP 5.2 adds
$strict
mode
Example #1 (print the result):
<?php
$b64 = 'Z3VydQ==';
echo base64_decode($b64); //-> "guru"
Example #2 (store the result in a variable and check for errors):
<?php
$b64 = 'SGVsbG8gV29ybGQhIQ==';
$str = base64_decode($b64);
if ($str === false) {
echo 'Invalid input';
} else {
echo $str; //-> "Hello World!!"
}
Example #3 (invalid type of $data
triggers E_WARNING “base64_decode() expects parameter 1 to be string, array given”):
<?php
echo base64_encode([]); //-> FALSE
Example #4 (the differences between the default mode and $strict
mode):
<?php
echo base64_decode('What?!'); //-> "Z�"
echo base64_decode('What?!', true); //-> FALSE
For more info, check the following examples:
Comments (15)
I hope you enjoy this discussion. In any case, I ask you to join it.