Перевод в base64 php

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

Источник

How to do Base64 Encoding and Decoding in PHP?

PHP is known to be the most widely used general-purpose programming language. It is basically a scripting language that is mainly used for web development. The reason for the popularity of this language is due to the fact that its syntax is extremely concise and simple. It means that it is capable of shrinking a lengthy code written in some other programming language into a few lines of code. As far as today’s article is concerned, then we will try to learn the concept of Base64 encoding and decoding using the PHP programming language.

Compiler Used

For creating a PHP script for the Base64 encoding and decoding and compiling it, later on, we used an online compiler.

In this guide, we wanted to focus more on the actual code rather than on the compiler used. This is exactly why we freed ourselves up from the hassle of installing a dedicated compiler for executing our PHP script; rather, we preferred using an online one. However, you can also use Visual Studio, Visual Studio Code, or any other compiler of your choice if you wish so.

Operating System Used

For this particular article, we have used the Windows 10 operating system, and we have accessed the online PHP compiler by using the Google Chrome browser; however, you can pick any operating system or browser of your choice for using this compiler.

The Built-in Encode and Decode Functions of PHP and their Parameters

The PHP programming language contains built-in functions for doing the Base64 encoding and decoding. The PHP function that is used for the Base64 encoding is “base64_encode,” whereas the one used for decoding is “base64_decode”. Both these functions accept a single parameter. The encoding function takes a normal string as the input, whereas the decoding function takes an encoded string as the input. Moreover, the return type of both of these functions is also “string.” The general syntaxes of both of these functions are given below:

Here, “StringToBeEncoded” represents the string that you want to encode.

Here, “StringToBeDecoded” refers to the string that you wish to decode.

These two built-in functions of PHP make it extremely convenient to do the Base64 encoding and decoding as needed. You literally need to write a single line of code for performing each of these processes, and you will realize it once you will go through the PHP script that we have designed for you.

The Process of Performing the Base64 Encoding and Decoding in PHP

The PHP script for performing the Base64 encoding and decoding is very simple. You need to take a look at this script first, and then we will try to explain it to you.

In this PHP script, we have first placed the PHP tag i.e. . The entire PHP script will be enclosed within this tag. Anything you will write outside this tag will not be executed. Then, we have created a variable “$str” and have equalized it to the string “I am a sample string.” For printing this string on the console, we have used the statement “echo nl2br(“The original string is: $str \n”).” The “echo” command in PHP is used for printing anything on the console. The “nl2br” function is used for inserting a newline after the current statement when used in conjunction with the “\n” flag just to enhance the readability of the output. Inside this function, we have written a message and the original string that is to be printed.

Then, we have created a variable named “$encoded” and have equalized it to the built-in PHP function “base64_encode”. This function takes a string as an input. We have passed the original string to this function. Then, we have used the same “echo” statement for printing the encoded string on the console. After that, we have created a variable named “$decoded” and have equalized it to the built-in PHP function “base64_decode”. This function takes an encoded string as input. Therefore, we have passed our encoded string to it, and then we have printed the decoded string on the console by using another “echo” command.

Result of the PHP Script for the Base64 Encoding and Decoding

After creating this PHP script, we wanted to visualize its results to confirm if the Base64 encoding and decoding have taken place successfully or not. For that, we had to execute this PHP script by clicking on the “Run” button located on our compiler. The result of this PHP script is shown in the image below:

In this result, you can easily see two normal strings, i.e., one original and the other decoded and one encoded string. The original and the decoded strings exactly match each other, which is an indication that the encoding and decoding processes have worked perfectly well in PHP. Moreover, since there were very few lines of code present in this PHP script, therefore, the execution of this PHP script took place at a very fast speed.

Conclusion

With the help of this guide, we wanted to convey to our readers the method of the Base64 encoding and decoding in the PHP programming language. For doing so, we accessed an online compiler whose link is also mentioned at the beginning of this article. Then, using this compiler, we designed a PHP script by using the built-in Base64 encoding and decoding functions of PHP. After that, we explained this script in detail to you, followed by its result. By going through this script and its respective result, you will be able to realize how easy it is to perform the Base64 encoding and decoding in the PHP programming language. All you need to take care of while writing a PHP script is that you do not write anything outside the PHP tag. Otherwise, you will not be capable of executing it ever.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.

Источник

Преобразование изображения в Base64 на PHP

Преобразование файла в Base64-изображение для вставки тег или CSS background производится по следующему формату:

Структура изображения Base64

Изображение для преобразования в base64

Для теста возьмем маленькое изображение: Для него в PHP нужно получить MIME, прочитать файл и закодировать полученные данные функцией base64_encode() . Т.к. функция getimagesize() не актуальна для SVG файлов, для них придется сделать исключение.

Результат:

Источник

Перевод в base64 php

Для того, чтобы преобразовать картинку в код base64 вам понадобится:

Нам потребуется картинка. возьмем её отсюда:

Выведем её здесь с помощью img :

Получаем картинку с помощью file_get_contents + сразу обработаем функцией «base64_encode» .

Картинка преобразованная в base64 будет иметь вид:

Весь код смотри под кнопкой «показать»

Зачем так делать непонятно, но в качестве примера. можно посмотреть:

Результат:

Источник

Читайте также:  Python call rest api
Оцените статью