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

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 as STRING
  • base64_decode($data, true) - Enables $strict mode and returns STRING if $data contains only Base64 characters

Arguments:

  • $data (required string) - The Base64 value you want to decode
  • $strict (optional boolean; default FALSE) - Specify TRUE 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 boolean FALSE

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 (1)

I hope you enjoy this discussion. In any case, I ask you to join it.

  • ChristianRodvel,
    Hola buen día, primero que nada felicidades por tu página, vi varias herramientas, sobre todo la herramienta que decodifica base64 y muestra un archivo pdf, misma que necesito replicar en una página que estoy realizando en la que obtengo un string de una api y debo generar el pdf así como lo haces tu en tu herramienta, solo que no encuentro como generarlo.
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.