A virtual teacher who reveals to you the great secrets of Base64

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.


  • base64_encode($data) - Encodes $data to Base64 and returns value as STRING


  • $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 boolean FALSE

Supported Versions:

  • PHP 4
  • PHP 5
  • PHP 7

Example #1 (print the result):

$str = 'guru';
echo base64_encode($str); //-> "Z3VydQ=="

Example #2 (store the result in a variable and check for errors):

$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”):

echo base64_encode([]); //-> FALSE

For more info, check the following examples:

Add new comment

If you have any questions, remarks, need help, or just like this page, please feel free to let me know by leaving a comment using the form bellow.
I will be happy to read every comment and, if necessary, I will do my best to respond as quickly as possible. Of course, spammers are welcome only as readers.