(PHP 4, PHP 5)

base64_decodeДекодирует данные, закодированные алгоритмом MIME base64


string base64_decode ( string $data [, bool $strict = false ] )

Декодирует строку data, закодированную при помощи base64.

Список параметров


Закодированные данные.


Возвращает FALSE, если данные содержат символы вне алфавита base64.

Возвращаемые значения

Возвращает декодированные данные или FALSE в случае возникновения ошибки. Возвращаемые данные могут быть бинарными.

Список изменений

Версия Описание
5.2.0 Добавлен параметр strict


Пример #1 Пример использования base64_decode()


Результат выполнения данного примера:

This is an encoded string

Смотрите также


I used to do uudecode as a C module, but I've discovered a really fast way to do it in PHP. Here it is:

function uudecode($encode) {

$encode preg_replace("/^./m","",$encode);
$encode preg_replace("/\n/m","",$encode);
$i=0$i<strlen($encode); $i++) {
    if (
$encode[$i] == '`')
$encode[$i] = ' ';
$encode[$i] = $b64chars[ord($encode[$i])-32];

strlen($encode) % 4)
$encode .= "=";


This is the PHP equivalent to perl's unpack("u",___). That is, you need to strip the 'begin' and 'end' lines from the typical uuencoded file.
2002-03-21 15:15:45
this script can correct the bug

$enc base64_decode($enc);
2003-04-17 07:05:16
I was wondering how to decode attached images within mails. Basically they are mostly JPEG files, so it was obviously to write a function that decodes JPEG images.
I guess the plainest way to do so was the following:

function base64_to_jpeg$inputfile$outputfile ) {
/* read data (binary) */
$ifp fopen$inputfile"rb" );
$imageData fread$ifpfilesize$inputfile ) );
fclose$ifp );
/* encode & write data (binary) */
$ifp fopen$outputfile"wb" );
fwrite$ifpbase64_decode$imageData ) );
fclose$ifp );
/* return output filename */
return( $outputfile );

This function decodes the given inputfile (a filename!) and saves it to the given outputfile (a filename as well) and then returns the output filename for further usage (e.g. redirect, imagejpeg() and so on).
I thought that might be helpful.
2003-12-23 14:16:50
To expand on Jes' post:

The change took place between 5.0.5 and 5.1.0.  Exactly where I don't know or care.

In short php <= 5.0.5's base64_decode( $string ) will assume that a space is meant to be a + sign where php >= 5.1.0's base64_decode( $string ) will no longer make that assumption.  I did not see this noted in the change log.

Please note that, as of this writing, mb_convert_encoding( $string, "UTF-8", "BASE64" ) still behaves as base64_decode( $string ) did in php <= 5.0.5 regardless of the version of php you are running.
2006-09-19 09:23:43
This function supports "base64url" as described in Section 5 of RFC 4648, "Base 64 Encoding with URL and Filename Safe Alphabet"

function base64url_decode($base64url)
$base64 strtr($base64url'-_''+/');
$plainText base64_decode($base64);
        return (
2006-12-06 12:23:14
Here is a drop-in replacement for base64_decode(), based on a faster version of morgangalpin's code:

// workaround for bug in php 4.3.11 through 4.4.7, 5.1.2 through 5.2.4 and perhaps others (
function    base64_decode_fix$data$strict false )
$strict )
preg_match'![^a-zA-Z0-9/+=]!'$data ) )
false );
base64_decode$data ) );
2007-11-10 16:22:12
@morgangalpin att gmail dotty com

A better implementation would be the following regular expression:


Which will also detect the usage of = or == at the end of the string (and only end).

If this regex isn't following proper RFC guidelines, please comment on it.

A function geared specifically toward this:


function is_base64_encoded()
        if (
preg_match('%^[a-zA-Z0-9/+]*={0,2}$%'$data)) {
        } else {

is_base64_encoded("iash21iawhdj98UH3"); // true
is_base64_encoded("#iu3498r"); // false
is_base64_encoded("asiudfh9w=8uihf"); // false
is_base64_encoded("a398UIhnj43f/1!+sadfh3w84hduihhjw=="); // true

2008-02-27 14:39:47
To follow up on Starson's post, PHP was changed to no longer treat a space as if it were a plus sign in CVS revision, which corresponds to PHP 5.1.0.  You can see what happened with a diff to branch point 1.43 at:

The CVS log indicates that this change was made to fix bug #34214 (base64_decode() does not properly ignore whitespace).

It would seem from the comment preceding the code which was removed that the treatment of the space as if it were the plus sign was actually intentional at one time:

    When Base64 gets POSTed, all pluses are interpreted as spaces.
    This line changes them back.  It's not exactly the Base64 spec,
    but it is completely compatible with it (the spec says that spaces
    are invalid).  This will also save many people considerable

    if (ch == ' ') ch = '+';

However, RFC 3548 states that characters not in the Base64 alphabet should either be ignored or cause the implementation to reject the encoding and RFC 2045 says they should be ignored.  So the original code was unfortunately not fully compatible with the spec or other implementations.  It may have also masked problems with code not properly escaping POST variables.
2008-07-09 23:38:15
You can do partial decoding (e.g. from buffered input streams) if you choose a chunk length that is multiple of 4:


base64_encode('The quick brown fox jumps over the lazy dog');
$i=0$len=strlen($encoded); $i<$len$i+=4){
base64_decodesubstr($encoded$i4) );


4 encoded chars represent 3 original chars. The "=" character is used as padding.
2008-12-05 03:11:13
I had a problem testing whether an imap message body was base64 encoded on a pre 5.2.* server.  I had been using this function on a post 5.2 server.

I found that the function imap_base64() returns FALSE on failing to decode a string, and that I could use that to check instead.

if(imap_base64($body)) $body imap_base64($body);
2009-04-09 12:20:05
Here is function to decode Base 62 (see string to number. It is used by MTA in message id, e.g. by Exim
function base62_decode($str) {
    for (
$i0$lstrlen($str); $i $l$i++) {
        if (
$val-= ord('0');
        else if (
$val-= ord('A') - 10;
        else if (
$val-= ord('a') - 36;
$ret$ret 62 $val;
2009-07-10 14:44:15
I had some trouble trying to let base64_decode decode base64-strings longer than ~5k chars.

The base64-decoding function is a homomorphism between modulo 4 and modulo 3-length segmented strings. That motivates a divide and conquer approach: Split the encoded string into substrings counting modulo 4 chars, then decode each substring and concatenate all of them.

Then instead of 

<?php $decoded base64_decode($encoded); ?>

for big $encoded strings, it's saver to use

for (
$i=0$i ceil(strlen($encoded)/256); $i++)
$decoded $decoded base64_decode(substr($encoded,$i*256,256));

where 256 can be replaced by a sufficiently small modulo 4 natural.
2009-08-18 00:05:21
If you want to save data that is derived from a Javascript canvas.toDataURL() function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:

str_replace(' ','+',$encodedData);
$decocedData base64_decode($encodedData);
2011-01-27 06:25:13
base64_decode seems to fail when decoding big files/strings. I had an issue decoding a 7MB image file. Here is a solution that worked for me:

2011-08-23 20:17:05
Base64 for URL parameters/filenames, that adhere to RFC 4648.
Defaults to dropping the padding on encode since it's not required for decoding, and keeps the URL free of % encodings.

function base64url_encode($data$pad null) {
$data str_replace(array('+''/'), array('-''_'), base64_encode($data));
    if (!
$pad) {
$data rtrim($data'=');
base64url_decode($data) {
base64_decode(str_replace(array('-''_'), array('+''/'), $data));
2015-11-02 08:58:51
The docs don't make this explicitly clear, but if you omit `$strict` or set it to `false` then invalid characters in the encoded input will be silently ignored.


echo base64_decode('VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw=='); // "This is an encoded string"
echo base64_decode('$VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw=='); // "This is an encoded string"
echo base64_decode('$VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw=='true); // false

2016-02-08 18:34:49
function is_base64($str){
        if($str === base64_encode(base64_decode($str))){
            return true;
        return false;


    $str = 'VGhpcyBpcyBiYXNlNjQgZW5jb2RlIHN0cmluZw==';

        print base64_decode($str);
2019-07-07 11:03:31

    Поддержать сайт на родительском проекте КГБ