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

Источник

Base64 encode php пример

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

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

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

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

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

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

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

Результат:

Источник

How to Use Base64 Encoding in PHP

Sajal Soni

Sajal Soni Last updated Apr 19, 2021

In this quick article, we’ll discuss the basics of base64 encoding in the context of PHP. Basically, we’ll see how you could use PHP functions to transform data into the base64-encoded format.

What Is Base64 Encoding?

Base64 is an encoding of binary data in ASCII. Each character in the string represents six bits of information. Effectively it represents the binary data in base 64 representation. Check out this primer on number systems and bases if you need a refresher.

The primary use of Base64 encoding is to encode binary data to ASCII text, when you want to transfer such data over protocols that are specifically designed to handle textual data. This makes sure that the data remains intact while it’s transported. Specifically, Base64 is used for things like sending emails and uploading binary data in HTML forms.

Another common use of Base64 encoding is hashing. Of course, you’re not supposed to use Base64 encoding itself to generate hashes, since it can be easily decoded. Firstly, you generate a hash with the help of a hashing algorithm like SHA, and then you convert the resulting hash into the Base64-encoded format to display it. It’s really easy to compare two Base64-encoded checksums for integrity.

In the next section, we’ll discuss the built-in Base64 functions in PHP.

Base64 Functions in PHP

There are two main functions in PHP that deal with Base64 encoding. The base64_encode function allows you to encode data in the MIME Base64 format. On the other hand, the base64_decode function is used to decode the MIME Base64-encoded data.

Let’s go through each of these functions in detail.

base64_encode

Let’s go through the syntax of the base64_encode function.

base64_encode ( string $string ) : string 

The only argument you need to pass to the base64_encode function is the source string which you want to encode to MIME Base64.

This returns a Base64-encoded string. It’s important to note that the Base64-encoded data takes around 33% more space in memory than the original data.

base64_decode

Let’s go through the syntax of the base64_decode function.

base64_decode ( string $string , bool $strict = false ) : string|false 

The first argument is the Base64-encoded data which you want to decode.

The second argument is optional, but if you pass TRUE , it will perform strict checking. This means that if the Base64-encoded data contains characters from outside the Base64 alphabet, the decode function will return FALSE . This is useful for checking the integrity of the Base64-encoded string. On the other hand, if you want to discard invalid characters silently, just pass FALSE , which is the default value.

On successful decoding, the function returns the decoded string, otherwise it returns FALSE . It’s important to note that the base64_decode function may return binary data if the string in question was in the binary format before encoding.

In the next section, we’ll discuss how you can use built-in Base64 functions in PHP.

How to Encode and Decode Data With MIME Base64

In this section, we’ll go through a couple of examples to see Base64 functions in action.

Encode URL Parameters

More often than not, you’ll end up using the base64_encode function to encode parameters that contain URLs.

Let’s quickly see how it works with the following example.

$redirectUrl = 'https://www.example.com/some/other/url'; 
header('Location: https://www.example.com/redirect/' . base64_encode($redirectUrl)); 
//https://www.example.com/redirect/aHR0cDovL3d3dy5leGFtcGxlLmNvbS9zb21lL290aGVyL3VybA== 

As you can see, if we don’t use the base64_encode function, the resulting URL would look like https://www.example.com/redirect/http://www.example.com/some/other/url , which is invalid.

Base64-Encoded Checksum

As we discussed earlier, the base64_encode function comes in handy when converting binary data into an ASCII string.

Let’s have a look at the following example.

$base64_encoded_hash = base64_encode(hash_hmac('sha1', 'Source string to be hashed.', 'YOUR_TOP_SECRET_KEY', true)); 

In the above example, the hash_hmac function would return hashed binary data. So if you don’t use the base64_encode function, it would be difficult to display the resulting binary data.

Email Attachments

In PHP, when you send an email with file attachments, you can encode the file contents into the Base64-encoded format. In fact, if you’re sending binary attachments, then it’s essential that you encode the attachment data instead of sending it in the raw format.

Let’s have a look at the following example.

$subject = 'Example of base64 encoded attachments'; 
$message = 'This email contains an image attachment.'; 
$headers .= "MIME-Version: 1.0" . "\r\n"; 
$headers .= "Content-Type: multipart/mixed; boundary color: #90a959">. $boundary . "\r\n"; 
$headers .= "Multipart MIME example." . "\r\n"; 
$message.= "Content-Type: text/plain; charset=\"iso-8859-1\"" . "\r\n"; 
$message.= "Content-Transfer-Encoding: 8bit" . "\r\n"; 
$filecontents = file_get_contents($filename); 
$filecontents = chunk_split(base64_encode($filecontents)); 
$message.= "Content-Type: image/jpg; name=\"" . $filename . "\"" . "\r\n"; 
$message.= "Content-Transfer-Encoding: base64" . "\r\n"; 
$message.= "Content-Disposition: attachment" . "\r\n"; 
mail($mailto, $subject, $body, $headers); 

As you can see, we’ve used the base64_encode function to encode binary image data before it’s sent as an attachment.

In this way, you can use Base64 functions in PHP for various purposes.

Conclusion

In this quick article, we discussed how you can use Base64 functions in your day-to-day PHP development.

Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.

Sajal Soni

I’m a software engineer by profession, and I’ve done my engineering in computer science. It’s been around 14 years I’ve been working in the field of website development and open-source technologies. Primarily, I work on PHP and MySQL-based projects and frameworks. Among them, I’ve worked on web frameworks like CodeIgnitor, Symfony, and Laravel. Apart from that, I’ve also had the chance to work on different CMS systems like Joomla, Drupal, and WordPress, and e-commerce systems like Magento, OpenCart, WooCommerce, and Drupal Commerce. I also like to attend community tech conferences, and as a part of that, I attended the 2016 Joomla World Conference held in Bangalore (India) and 2018 DrupalCon which was held in Mumbai (India). Apart from this, I like to travel, explore new places, and listen to music!

Источник

Читайте также:  Vk apps mini python
Оцените статью