php base64 url encode

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.

php base64 url encode. Смотреть фото php base64 url encode. Смотреть картинку php base64 url encode. Картинка про php base64 url encode. Фото php base64 url encode

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

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

Источник

Выводим изображение в кодировке Base64 на HTML/CSS и сохраняем его на jQuery+PHP

Base64 – это некий стандарт кодирования информации посредством только 64 символов таблицы ASCII. В эту таблицу входят символы латинского языка (A-Z и a-z), цифры от 0 до 9, а также некоторые знаки.

Принцип этого кодирования – представление любой цифровой информации в виде уникального набора символов этой таблицы.

Чтобы вы наглядно понимали, что это такое, поясню. Перед вами изображение:

php base64 url encode. Смотреть фото php base64 url encode. Смотреть картинку php base64 url encode. Картинка про php base64 url encode. Фото php base64 url encode

А вот его кодировка Base64:

Что нас здесь интересует? Как сохранить такие данные и представить их в читабельном виде на примере все тех же изображений.

Выводим изображение в формате Base64 на HTML/CSS

В HTML встраивание подобного рода кода осуществляется с помощью всем привычного тега IMG. И на примере все той же картинки результат будет следующим:

Помимо этого, Base64 можно встроить и в CSS-файл:

Какие есть преимущества у этой кодировки? Основное преимущество – это то, что изображения вы не храните на своем сервере и вообще ни на каком в принципе, а просто размещаете нужные вам файлы в теле страницы обычным текстом.

Сохранение изображения в формате Base64 на jQuery+PHP

Чуть выше мы разобрали с вами встраивание изображений непосредственно в страницу вашего сайта с помощью HTML и CSS, а сейчас мы рассмотрим способ сохранения такого изображения на вашем сайте.

В одной из статей был рассмотрен вопрос о том, как же сделать скриншот элемента на JavaScript, используя библиотеку html2canvas. В примере мы рассматривали скриншот как уже готовое изображение, но мы не упомянули, что при использовании там кода:

можно получить изображение как раз в кодировке Base64.

Давайте попробуем сохранить это (вы можете использовать свое) изображение в кодировке Base64, используя технологию AJAX и не большой PHP-скрипт.

Начнем с jQuery. Скрипт, который будет посылать в обработчик (PHP-скрипт) наши данные, будет выглядеть следующим образом:

Где «base_image» – данные изображения в Base64, «/upload/base-image.php» – путь до PHP-скрипта, а «#result» – ID элемента, в который будет выводиться результат.

Сам же скрипт-обработчик будет выглядеть следующим образом:

Здесь все предельно просто – получаем данные, обрабатываем и сохраняем их в той же директории, что и сам обработчик.

В качестве функции запуска я использовал обычную загрузку страницы, вы же можете привязать ее, например, к клику по ссылке или другому нужному вам действию.

Расписал вроде все максимально подробно, но если какие-то моменты вызывают у вас трудности, не стесняйтесь и задавайте их в комментариях – никого не оставим без внимания.

Источник

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.

Источник

urlencode

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

urlencode — URL-кодирование строки

Описание

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

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

Строка, которая должна быть закодирована.

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

Примеры

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

Пример #2 Пример использования urlencode() и htmlentities()

Примечания

Будьте внимательны с переменными, которые могут совпадать с элементами HTML. Такие сущности как &amp, &copy и &pound разбираются браузером и используется как реальная сущность, а не желаемое имя переменной. Это очевидный конфликт, на который W3C указывает в течение многих лет. Смотрите подробности: » http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2

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

User Contributed Notes 25 notes

urlencode function and rawurlencode are mostly based on RFC 1738.

However, since 2005 the current RFC in use for URIs standard is RFC 3986.

Here is a function to encode URLs according to RFC 3986.

I needed encoding and decoding for UTF8 urls, I came up with these very simple fuctions. Hope this helps!

Don’t use urlencode() or urldecode() if the text includes an email address, as it destroys the «+» character, a perfectly valid email address character.

Unless you’re certain that you won’t be encoding email addresses AND you need the readability provided by the non-standard «+» usage, instead always use use rawurlencode() or rawurldecode().

I needed a function in PHP to do the same job as the complete escape function in Javascript. It took me some time not to find it. But findaly I decided to write my own code. So just to save time:

urlencode is useful when using certain URL shortener services.

The returned URL from the shortener may be truncated if not encoded. Ensure the URL is encoded before passing it to a shortener.

(tilde), while urlencode does.

Below is our jsonform source code in mongo db which consists a lot of double quotes. we are able to pass this source code to the ajax form submit function by using php urlencode :

If you want to pass a url with parameters as a value IN a url AND through a javascript function, such as.

. pass the url value through the PHP urlencode() function twice, like this.

However, some weird things happen when dealing with characters like (these are HTML entities): ‼ ▐ ┐and Θ have weird things going on.

If you try to pass one in Internet Explorer, IE will *disable* the submit button. Firefox, however, does something weirder: it will convert it to it’s HTML entity. It will display properly, but only when you don’t convert entities.

The point? Be careful with decorative characters.

This very simple function makes an valid parameters part of an URL, to me it looks like several of the other versions here are decoding wrongly as they do not convert & seperating the variables into &.

$vars=array(‘name’ => ‘tore’,’action’ => ‘sell&buy’);
echo MakeRequestUrl($vars);

Will output: action=sell%26buy&name=tore

Constructing hyperlinks safely HOW-TO:

= ‘machine/generated/part’ ;
$url_parameter1 = ‘this is a string’ ;
$url_parameter2 = ‘special/weird «$characters»‘ ;

$link_label = «Click here & you’ll be » ;

Shortly:
— Use urlencode for all GET parameters (things that come after each «=»).
— Use rawurlencode for parts that come before «?».
— Use htmlspecialchars for HTML tag parameters and HTML text content.

look on index.php
array (size=0)
empty
test-bla-bla-4%253E2-y-3%253C6

look on test-bla-bla-4%253E2-y-3%253C6
array (size=1)
‘token’ => string ‘bla-bla-4>2-y-3

Simple static class for array URL encoding

/**
*
* URL Encoding class
* Use : urlencode_array::go() as function
*
*/
class urlencode_array
<

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *