Php base64 decode кириллица

base64_encode

Эта кодировка предназначена для корректной передачи бинарных данных по протоколам, не поддерживающим 8-битную передачу, например, для отправки тела письма.

Данные, закодированные base64 занимают на 33% больше места по сравнению с оригинальными данными.

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

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

Кодированные данные в виде строки.

Примеры

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

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

0K3RgtC+INC30LDQutC+0LTQuNGA0L7QstCw0L3QvdCw0Y8g0YHRgtGA0L7QutCw

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

  • base64_decode() — Декодирует данные, закодированные MIME base64
  • chunk_split() — Разбивает строку на фрагменты
  • convert_uuencode() — Кодирует строку в формат uuencode
  • » RFC 2045 раздел 6.8

User Contributed Notes 37 notes

For anyone interested in the ‘base64url’ variant encoding, you can use this pair of functions:

function base64url_encode ( $data ) <
return rtrim ( strtr ( base64_encode ( $data ), ‘+/’ , ‘-_’ ), ‘=’ );
>

function base64url_decode ( $data ) <
return base64_decode ( str_pad ( strtr ( $data , ‘-_’ , ‘+/’ ), strlen ( $data ) % 4 , ‘=’ , STR_PAD_RIGHT ));
>
?>

gutzmer at usa dot net’s ( http://php.net/manual/en/function.base64-encode.php#103849 ) base64url_decode() function doesn’t pad longer strings with ‘=’s. Here is a corrected version:

function base64url_encode ( $data ) return rtrim ( strtr ( base64_encode ( $data ), ‘+/’ , ‘-_’ ), ‘=’ );
>

function base64url_decode ( $data ) return base64_decode ( strtr ( $data , ‘-_’ , ‘+/’ ) . str_repeat ( ‘=’ , 3 — ( 3 + strlen ( $data )) % 4 ));
>

// proof
for( $i = 0 , $s = » ; $i < 24 ; ++ $i , $s .= substr ( " $i " , - 1 ))$base64_encoded = base64_encode ( $s );
$base64url_encoded = base64url_encode ( $s );
$base64url_decoded = base64url_decode ( $base64url_encoded );
$base64_restored = strtr ( $base64url_encoded , ‘-_’ , ‘+/’ )
. str_repeat ( ‘=’ ,
3 — ( 3 + strlen ( $base64url_encoded )) % 4
);
echo » $s
$base64url_decoded
$base64_encoded
$base64_restored
$base64url_encoded

» ;
>
?>

In PHP 7, the padding issue with base64_decode() is no more — the following is totally fine:

function base64_encode_url($string) return str_replace([‘+’,’/’,’=’], [‘-‘,’_’,»], base64_encode($string));
>

function base64_decode_url($string) return base64_decode(str_replace([‘-‘,’_’], [‘+’,’/’], $string));
>

Checked here with random_bytes() and random lengths:

Base64 encoding of large files.

Base64 encoding converts triples of eight-bit symbols into quadruples of six-bit symbols. Reading the input file in chunks that are a multiple of three bytes in length results in a chunk that can be encoded independently of the rest of the input file. MIME additionally enforces a line length of 76 characters plus the CRLF. 76 characters is enough for 19 quadruples of six-bit symbols thus representing 19 triples of eight-bit symbols. Reading 57 eight-bit symbols provides exactly enough data for a complete MIME-formatted line. Finally, PHP’s default buffer size is 8192 bytes — enough for 143 MIME lines’ worth of input.

So if you read from the input file in chunks of 8151 (=57*143) bytes you will get (up to) 8151 eight-bit symbols, which encode as exactly 10868 six-bit symbols, which then wrap to exactly 143 MIME-formatted lines. There is no need to retain left-over symbols (either six- or eight-bit) from one chunk to the next. Just read a chunk, encode it, write it out, and go on to the next chunk. Obviously the last chunk will probably be shorter, but encoding it is still independent of the rest.

while(! feof ( $input_file ))
$plain = fread ( $input_file , 57 * 143 );
$encoded = base64_encode ( $plain );
$encoded = chunk_split ( $encoded , 76 , «\r\n» );
fwrite ( $output_file , $encoded );
>

?>

Conversely, each 76-character MIME-formatted line (not counting the trailing CRLF) contains exactly enough data for 57 bytes of output without needing to retain leftover bits that need prepending to the next line. What that means is that each line can be decoded independently of the others, and the decoded chunks can then be concatenated together or written out sequentially. However, this does make the assumption that the encoded data really is MIME-formatted; without that assurance it is necessary to accept that the base64 data won’t be so conveniently arranged.

Unfortunately my «function» for encoding base64 on-the-fly from 2007 [which has been removed from the manual in favor of this post] had 2 errors!
The first led to an endless loop because of a missing «$feof»-check, the second caused the rare mentioned errors when encoding failed for some reason in larger files, especially when
setting fgets($fh, 2) for example. But lower values then 1024 are bad overall because they slow down the whole process, so 4096 will be fine for all purposes, I guess.
The error was caused by the use of «empty()».

Here comes the corrected version which I have tested for all kind of files and length (up to 4,5 Gb!) without any error:

$fh = fopen ( ‘Input-File’ , ‘rb’ );
//$fh2 = fopen(‘Output-File’, ‘wb’);

if (! $eof ) <
if (! feof ( $fh )) <
$row = fgets ( $fh , 4096 );
> else <
$row = » ;
$eof = true ;
>
>

if ( $cache !== » )
$row = $cache . $row ;
elseif ( $eof )
break;

$b64 = base64_encode ( $row );
$put = » ;

if ( strlen ( $b64 ) < 76 ) <
if ( $eof ) <
$put = $b64 . «\n» ;
$cache = » ;
> else <
$cache = $row ;
>

> elseif ( strlen ( $b64 ) > 76 ) <
do <
$put .= substr ( $b64 , 0 , 76 ). «\n» ;
$b64 = substr ( $b64 , 76 );
> while ( strlen ( $b64 ) > 76 );

$cache = base64_decode ( $b64 );

if ( $put !== » ) <
echo $put ;
//fputs($fh2, $put);
//fputs($fh2, base64_decode($put)); // for comparing
>
>

Источник

base64_decode

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

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

Если параметр strict задан как true , функция base64_decode() вернёт false в случае, если входные данные содержат символы, не входящие в алфавит base64. В противном случае такие символы будут отброшены.

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

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

Примеры

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

$str = ‘0K3RgtC+INC30LDQutC+0LTQuNGA0L7QstCw0L3QvdCw0Y8g0YHRgtGA0L7QutCw’ ;
echo base64_decode ( $str );
?>

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

Это закодированная строка

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

User Contributed Notes 17 notes

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:

$encodedData = str_replace ( ‘ ‘ , ‘+’ , $encodedData );
$decocedData = base64_decode ( $encodedData );
?>

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.

$decoded = «» ;
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.

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 ( $plainText );
>
?>

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 , ‘=’ );
>
return $data ;
>
function base64url_decode ( $data ) return base64_decode ( str_replace (array( ‘-‘ , ‘_’ ), array( ‘+’ , ‘/’ ), $data ));
>

@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/+]*=$%’ , $data )) return TRUE ;
> else return FALSE ;
>
>;

is_base64_encoded ( «iash21iawhdj98UH3» ); // true
is_base64_encoded ( «#iu3498r» ); // false
is_base64_encoded ( «asiudfh9w=8uihf» ); // false
is_base64_encoded ( «a398UIhnj43f/1!+sadfh3w84hduihhjw= keyword»>); // true

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 1.43.2.1, 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
headache.

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.

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

In short 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

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 ( $ifp , filesize ( $inputfile ) );
fclose ( $ifp );
/* encode & write data (binary) */
$ifp = fopen ( $outputfile , «wb» );
fwrite ( $ifp , base64_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.

Источник

Читайте также:  Replace links in text php
Оцените статью