base64 encode php utf 8

base64_decode

(PHP 4, PHP 5, PHP 7, PHP 8)

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

Описание

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

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

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

Примеры

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

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

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

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:

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.

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.

This function supports «base64url» as described in Section 5 of RFC 4648, «Base 64 Encoding with URL and Filename Safe Alphabet»

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.

Источник

base64_encode

(PHP 4, PHP 5, PHP 7, PHP 8)

base64_encode — Кодирует данные в формат MIME base64

Описание

Кодирует string с base64.

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

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

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

Данные для кодирования.

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

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

Примеры

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

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

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

User Contributed Notes 35 notes

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

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 base64_encode_url($string) <
return str_replace([‘+’,’/’,’=’], [‘-‘,’_’,»], base64_encode($string));
>

Checked here with random_bytes() and random lengths:

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:

$cache = » ;
$eof = false ;

Base64 encoding of large files.

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.

Читайте также:  Что такое цифровые технологии примеры

?>

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.

A function I’m using to return local images as base64 encrypted code, i.e. embedding the image source into the html request.

This will greatly reduce your page load time as the browser will only need to send one server request for the entire page, rather than multiple requests for the HTML and the images. Requests need to be uploaded and 99% of the world are limited on their upload speed to the server.

Источник

Some utf-8 strings base64 encoded by php can not be decoded using iOS base64 library?

Here is one piece of Chinese utf-8 text which is encoded by PHP on the server-side, but when I decode it with iOS, it returns null.

I also tried this online tool where text can be decoded well.

Here is the test code for debug this issue with xcode:

2 Answers 2

Your revised question features a base64 string of:

This string has a length that is a multiple of four bytes, so the lack of the = / == terminator at the end is not the problem. And, in fact, initWithBase64EncodedString decodes it successfully:

The issue here is that this appears to not be a valid UTF8 string. In fact, when I run it through the http://base64decode.net site you referenced in your original question, it is also unable to convert it to a UTF8 string (I notice that your screen snapshots are using a different converter web site). When I ran it through another converter, it converted what it could, but then complained about the character following 学了 (which is, coincidentally, the character at which your base64 converter web site stopped, too).

The original question featured a base64 string of:

That is not valid base64. It should be a multiple of four bytes in length, but that is only 163 characters, which is missing a character. Either your server isn’t properly terminating the base64 string, or it got cut off for some reason.

For example, if I add a = to get it up to 164 characters, I get a valid base64 string:

Adding the = would be the right solution if the server simply neglected to terminate the base64 string properly. Anyway, that can be base64-decoded to:

Is that what you were expecting?

Perhaps you should take a look at your base64 routine on your server? Or if it’s getting truncated, look at how you are receiving it and compare the server’s original base64 string length to what you have here.

For information about adding = or == to the end of a base 64 encoded string, see the base64 wikipedia page.

Источник

Passing base64 encoded strings in URL

Is it safe to pass raw base64 encoded strings via GET parameters?

9 Answers 9

There are additional base64 specs. (See the table here for specifics ). But essentially you need 65 chars to encode: 26 lowercase + 26 uppercase + 10 digits = 62.

You need two more [‘+’, ‘/’] and a padding char ‘=’. But none of them are url friendly, so just use different chars for them and you’re set. The standard ones from the chart above are [‘-‘, ‘_’], but you could use other chars as long as you decoded them the same, and didn’t need to share with others.

I’d recommend just writing your own helpers. Like these from the comments on the php manual page for base64_encode:

‘ (tilde) or ‘.’ (dot) instead.

Valid base64 characters are below.

Читайте также:  Что такое штампованные диски

@joeshmo Or instead of writing a helper function, you could just urlencode the base64 encoded string. This would do the exact same thing as your helper function, but without the need of two extra functions.

Introductory Note I’m inclined to post a few clarifications since some of the answers here were a little misleading (if not incorrect).

the result would be:
stringwith sign

The easy way to solve this is to simply urlencode() your base64 string before adding it to the query string to escape the +, =, and / characters to %## codes. For instance, urlencode(«stringwith+sign») returns stringwith%2Bsign

the result would is:
stringwith+sign

the result is an unexpected:
stringwith sign

It would be safe to rawurldecode() the input, however, it would be redundant and therefore unnecessary.

Источник

base64_encode

base64_encode — Kодирует данные алгоритмом MIME base64

Описание

Кодирует data алгоритмом base64.

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

Данные кодированные алгоритмом Base64 увеличиваются в объеме на 33% по сравнению с оригинальными данными.

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

Данные для кодирования.

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

Кодированные данные, как строку или FALSE в случае возникновения ошибки.

Примеры

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

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

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

Коментарии

You can use base64_encode to transfer image file into string text and then display them. I used this to store my images in a database and display them form there. First I open the files using fread, encoded the result, and stored that result in the database. Useful for creating random images.

?>

And in the html file you put:

If you use base64encoded strings as cookie names, make sure you remove ‘=’ characters. At least Internet Explorer refuses cookie names containing ‘=’ characters or urlencoded cookie names containing %xx character replacements. Use the function below to turn base64 encoded strings to bare alphabets (get rid of / and + characters as well)

I’ve used base64_encode and base64_decode for file attachment both in MySQL (using a BLOB field) and MSSQL (using a TEXT field). For MSSQL remember to set in PHP.INI file both mssql.textsize and mssql.textlimit to 2147483647.

######### MSSQL(mssql_)/MySQL(mysql_) file attach
$val=$HTTP_POST_FILES[‘lob_upload’][‘tmp_name’];
$valn=$HTTP_POST_FILES[‘lob_upload’][‘name’];
$valt=$HTTP_POST_FILES[‘lob_upload’][‘type’];

$data=base64_encode(addslashes(fread(fopen($val, «r»), filesize($val))));

This strategy is good for Microsoft Word, Acrobat PDF, JPG image and so on (even zipped files. )

If you encode text that contains symbols like and want to send it in GET query, be sure to urlencode the result of base64_encode, as it sometimes adds a + (and it’s a special symbol) at the end:

echo base64_encode ( ‘ ‘ );
?>

returns:

A function like this could also be useful:

If the function doesn’t exist, this is a messy but effective way of doing it:

echo bencode ( «Gabriel Malca» );
// R2FicmllbCBNYWxjYQ==

Php version of perl’s MIME::Base64::URLSafe, that provides an url-safe base64 string encoding/decoding (compatible with python base64’s urlsafe methods)

$data = str_replace(array(‘+’,’/’,’=’),array(‘-‘,’_’,),$data); // MIME::Base64::URLSafe implementation

$data = str_replace(array(‘+’,’/’),array(‘-‘,’_’),$data); // Python raise «TypeError: Incorrect padding» if you remove «=» chars when decoding

Just a minor tweak of massimo’s functions.

Using Function:
Output for HTML Put:

function getimage ($image) <
switch ($image) <
case ‘file’:
return base64_decode(‘R0lGODlhEQANAJEDAJmZmf///wAAAP///yH5BAHoAwMALAAAA
AARAA0AAAItnIGJxg0B42rsiSvCA/REmXQWhmnih3LUSGaqg35vF
bSXucbSabunjnMohq8CADsA’);
case ‘folder’:
return base64_decode(‘R0lGODlhEQANAJEDAJmZmf///8zMzP///yH5BAHoAwMALAAAAA
ARAA0AAAIqnI+ZwKwbYgTPtIudlbwLOgCBQJYmCYrn+m3smY5v
Gc+0a7dhjh7ZbygAADsA’);
case ‘hidden_file’:
return base64_decode(‘R0lGODlhEQANAJEDAMwAAP///5mZmf///yH5BAHoAwMALAAAA
AARAA0AAAItnIGJxg0B42rsiSvCA/REmXQWhmnih3LUSGaqg35vF
bSXucbSabunjnMohq8CADsA’);
case ‘link’:
return base64_decode(‘R0lGODlhEQANAKIEAJmZmf///wAAAMwAAP///wAAAAAAAAAAA
CH5BAHoAwQALAAAAAARAA0AAAM5SArcrDCCQOuLcIotwgTYUll
NOA0DxXkmhY4shM5zsMUKTY8gNgUvW6cnAaZgxMyIM2zBLCaHlJgAADsA’);
case ‘smiley’:
return base64_decode(‘R0lGODlhEQANAJECAAAAAP//AP///wAAACH5BAHoAwIALAAAA
AARAA0AAAIslI+pAu2wDAiz0jWD3hqmBzZf1VCleJQch0rkdnppB3
dKZuIygrMRE/oJDwUAOwA=’);
case ‘arrow’:
return base64_decode(‘R0lGODlhEQANAIABAAAAAP///yH5BAEKAAEALAAAAAARAA0AA
AIdjA9wy6gNQ4pwUmav0yvn+hhJiI3mCJ6otrIkxxQAOw==’);
>
>

This function supports «base64url» as described in Section 5 of RFC 4648, «Base 64 Encoding with URL and Filename Safe Alphabet»

I needed a simple way to obfuscate auto_increment primary keys in databases when they are visible to users in URIs or API calls. The users should not be able to increment the id in the URL and see the next data record in the database table.

My solution (uses modified base64 functions by Tom):

return base64url_encode($int.’-‘.substr(sha1($class.$int.encryptionKey), 0, 6));
>

— The optional 2nd argument is the class name, so two equal ids of different tables will not result in two equal obfuscated ids.

— encryptionKey is a global secret key for encryption.

— decryptId() checks if the second part of the base64 encoded string is correct.

I have another solution that is simple and elegant. Create a pseudorandom string of characters. Then, each time you want to obfuscate your key, append a random substring from the pseudorandom string and use base64 encoding. When you want to de-obfuscate, convert back from base64. If the prefix is not in your pseudorandom source, then the value is forged. Otherwise, strip the prefix and recover your original key.

Читайте также:  Что является мотивацией при выполнении работы примеры

The advantages are that the string will look different even for the same key, and encoding and decoding should be extremely fast.

I omitted the strtr functions in my examples. Here are corrected functions:

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:

$cache = » ;
$eof = false ;

Note that some applications, such as OpenSSL’s enc command, require that there be a line break every 64 characters in order for their base64 decode function to work. The following function will take care of this problem:

output images into html:

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

An even faster way to line-breaks every 64th character is using the chunk_split function:

A function I’m using to return local images as base64 encrypted code, i.e. embedding the image source into the html request.

This will greatly reduce your page load time as the browser will only need to send one server request for the entire page, rather than multiple requests for the HTML and the images. Requests need to be uploaded and 99% of the world are limited on their upload speed to the server.

Base64 encoding of large files.

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.

?>

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.

// Echo out a sample image
echo » » ;
?>

Wikipedia has a list of 8 or so variations on the last 2 characters in Base64 (https://en.wikipedia.org/wiki/Base64). The following functions can handle all of them:

@gutzmer at usa dot net

The function base64url_decode doesn’t pad strings longer than 4 chars.
str_pad will only pad the string if the second argument is larger than the length of the original string. So the correct function should be:

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

Regarding base64url, you can just use:

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

Checked here with random_bytes() and random lengths:

shortest base64url_decode (correct version)

if you for some reason need a base10 / pure-number encode instead, encoding to some combination of 0123456789

You can escape ‘+’, ‘/’ and ‘=’ symbols using two simple functions:

Источник

Образовательный портал