PHP Base64 Encode
To encode data in Base64, PHP provides a function called base64_encode
. The inverse transformation is achieved by using the function base64_decode. Unlike data decoding, the encoding function does not conceal any pitfalls.
Usage:
base64_encode($data)
- Encodes$data
to Base64 and returns value asSTRING
Arguments:
$data
(required string) - Text or binary content that you want to encode
Return Values:
STRING
- On success, it returns the Base64 value, typically longer by about 33% than$data
FALSE
- If a failure occurs (if$data
cannot be encoded to Base64), it returns booleanFALSE
Supported Versions:
- PHP 4
- PHP 5
- PHP 7
Example #1 (print the result):
<?php
$str = 'guru';
echo base64_encode($str); //-> "Z3VydQ=="
Example #2 (store the result in a variable and check for errors):
<?php
$str = 'Hello World!!';
$b64 = base64_encode($str);
if ($b64 === false) {
echo 'Invalid input';
} else {
echo $b64; //-> "SGVsbG8gV29ybGQhIQ=="
}
Example #3 (invalid type of $data
triggers E_WARNING “base64_encode() expects parameter 1 to be string, array given”):
<?php
echo base64_encode([]); //-> FALSE
For more info, check the following examples:
Comments (16)
I hope you enjoy this discussion. In any case, I ask you to join it.