Urlencode что это
Перейти к содержимому

Urlencode что это

  • автор:

urlencode

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

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

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

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

Возвращает строку, в которой все не цифробуквенные символы, кроме -_. должны быть заменены знаком процента (%), за которым следует два шестнадцатеричных числа, а пробелы кодируются как знак сложения (+). Строка кодируется тем же способом, что и POST данные WWW-формы, то есть по типу контента application/x-www-form-urlencoded. Это отличается от » RFC 3986 кодирования (см. rawurlencode() ) тем, что, по историческим соображениям, пробелы кодируются как знак «плюс» (+).

Примеры

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

echo ‘, urlencode ( $userinput ), ‘»>’ ;
?>

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

Функция urlencode() модуля urllib.parse в Python

Создать key=value строку из словаря для GET/POST запроса

Синтаксис:
import urllib.parse urllib.parse.urlencode(query, doseq=False, safe='', encoding=None, errors=None, quote_via=quote_plus) 
Параметры:
  • query — словарь ИЛИ последовательностькортежей из 2-х элементов,
  • doseq=False — создавать или нет одинаковые ключи для разных значений,
  • safe=» — символы ASCII, которые не следует кодировать,
  • encoding=None — исходная кодировка значений,
  • errors=None — обработчик ошибок кодировки,
  • quote_via=quote_plus — функция кодирования значений.
Возвращаемое значение:
  • строка представляющая ряд пар key=value , разделенных символами ‘&’ .
Описание:

Функция urlencode() модуля urllib.parse преобразует объект сопоставления (словарь) или последовательность кортежей, состоящих из 2-х элементов в текстовую ASCII строку с процентным кодированием.

Ключи и значения объекта сопоставления, а так же оба элемента кортежа, передаваемые в query могут иметь тип str ИЛИ bytes .

Результирующая строка представляет собой ряд пар key=value , разделенных символами ‘&’ , где и ключ key и значение value заключаются в кавычки с помощью функции для аргумента quote_via . Для цитирования значений, по умолчанию используется функция quote_plus() , это означает, что пробелы заключаются в кавычки, как символ ‘+’ , а символы ‘/’ кодируются как %2F , что соответствует стандарту для запросов GET ( application/x-www-form-urlencoded ). Альтернативной функцией, которая может быть передана как quote_via , является quote() , которая будет кодировать пробелы как %20 , а символы ‘/’ — кодировать не будет. Для максимального контроля того, что кодируется, используйте аргумент quote , а так же укажите значение аргумента safe .

Когда в качестве аргумента query используется последовательность двухэлементных кортежей, то первый элемент каждого кортежа является ключом, а второй — значением. Элемент value сам по себе может быть последовательностью, и в этом случае, если необязательный аргумент doseq принимает значение True , для каждого элемента последовательности значений ключа генерируются отдельные пары key=value , разделенные символом ‘&’ . Порядок параметров в кодированной строке будет соответствовать порядку кортежей параметров в последовательности.

Аргументы safe , encoding и errors передаются в quote_via (параметры encoding и errors передаются только в том случае, если элемент запроса является текстовой строкой str ).

Чтобы наоборот, разобрать строку с элементами POST/GET запроса в структуры данных Python, то нужно воспользоваться функциями этого модуля parse_qs() и parse_qsl() .

Примеры использования urllib.parse.urlencode() :

Используем функцию urllib.parse.urlencode() для генерации строки запроса URL-адреса или данных для POST-запроса.

Вот пример генерации URL-адреса, содержащего параметры для GET/POST запроса:

>>> import urllib.parse >>> query = 'spam': 1, 'eggs': 2, 'bacon': 'foo'> >>> params = urllib.parse.urlencode(query) >>> f'http://example.com/query?params>' # 'http://example.com/query?spam=1&eggs=2&bacon=foo' 

Поведение аргумента doseq

>>> import urllib.parse >>> query = 'spam': 1, 'bacon': ['foo', 'bar']> # doseq=False по умолчанию >>> urllib.parse.urlencode(query) # 'spam=1&bacon=%5B%27foo%27%2C+%27bar%27%5D' # doseq=True >>> urllib.parse.urlencode(query, doseq=True) # 'spam=1&bacon=foo&bacon=bar' 

Изменение функции кодирования quote_via .

>>> import urllib.parse >>> query = 'spam': 1, 'bacon': ['foo', 'bar']> >>> urllib.parse.urlencode(query, quote_via=urllib.parse.quote) # 'spam=1&bacon=%5B%27foo%27%2C%20%27bar%27%5D 

Передача списка кортежей, вместо словаря.

>>> import urllib.parse >>> query = [('spam': 1), ('bacon': ['foo', 'bar'])] >>> urllib.parse.urlencode(query, doseq=True) # 'spam=1&bacon=foo&bacon=bar' 
  • КРАТКИЙ ОБЗОР МАТЕРИАЛА.
  • Функция urlparse() модуля urllib.parse
  • Функция parse_qs() и parse_qsl() модуля urllib.parse
  • Функция urlunparse() модуля urllib.parse
  • Функция urlsplit() модуля urllib.parse
  • Функция urlunsplit() модуля urllib.parse
  • Функция urljoin() модуля urllib.parse
  • Функция urldefrag() модуля urllib.parse
  • Функция urlencode() модуля urllib.parse
  • Функция quote() и quote_plus() модуля urllib.parse
  • Функция unquote() и unquote_plus() модуля urllib.parse

urlencode

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

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

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

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

Возвращает строку, в которой все не цифро-буквенные символы, кроме -_. должны быть заменены знаком процента ( % ), за которым следует два шестнадцатеричных числа, а пробелы закодированы как знак сложения ( + ). Строка кодируется тем же способом, что и POST-данные веб-формы, то есть по типу контента application/x-www-form-urlencoded . Это отличается от кодирования по » RFC 3986 (смотрите rawurlencode() ) в том, что по историческим причинам, пробелы кодируются как знак «плюс» (+).

Примеры

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

$userinput = ‘Data123!@-_ +’ ;
echo «Пользовательские данные: $userinput \n» ;
echo ‘, urlencode ( $userinput ), ‘»>’ ;
?>

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

Пользовательские данные: Data123!@-_ +

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

$foo = ‘Data123!@-_ +’ ;
$bar = «Содержимое, отличное от $foo » ;
echo «foo: $foo \n» ;
echo «bar: $bar \n» ;
$query_string = ‘foo=’ . urlencode ( $foo ) . ‘&bar=’ . urlencode ( $bar );
echo ‘. htmlentities ( $query_string ) . ‘»>’ ;
?>

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

foo: Data123!@-_ + bar: Содержимое, отличное от Data123!@-_ +

Примечания

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

  • urldecode() — Декодирование URL-кодированной строки
  • htmlentities() — Преобразует все возможные символы в соответствующие HTML-сущности
  • rawurlencode() — URL-кодирование строки согласно RFC 3986
  • rawurldecode() — Декодирование URL-кодированной строки
  • » RFC 3986

User Contributed Notes 26 notes

13 years ago

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.

function myUrlEncode ( $string ) $entities = array( ‘%21’ , ‘%2A’ , ‘%27’ , ‘%28’ , ‘%29’ , ‘%3B’ , ‘%3A’ , ‘%40’ , ‘%26’ , ‘%3D’ , ‘%2B’ , ‘%24’ , ‘%2C’ , ‘%2F’ , ‘%3F’ , ‘%25’ , ‘%23’ , ‘%5B’ , ‘%5D’ );
$replacements = array( ‘!’ , ‘*’ , «‘» , «(» , «)» , «;» , «:» , «@» , «&» , » keyword»>, «+» , «$» , «,» , «/» , «?» , «%» , «#» , «[» , «]» );
return str_replace ( $entities , $replacements , urlencode ( $string ));
>
?>

14 years ago

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

function url_encode ( $string ) return urlencode ( utf8_encode ( $string ));
>

function url_decode ( $string ) return utf8_decode ( urldecode ( $string ));
>
?>

13 years ago

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:

function fullescape ( $in )
<
$out = » ;
for ( $i = 0 ; $i < strlen ( $in ); $i ++)
<
$hex = dechex ( ord ( $in [ $i ]));
if ( $hex == » )
$out = $out . urlencode ( $in [ $i ]);
else
$out = $out . ‘%’ .(( strlen ( $hex )== 1 ) ? ( ‘0’ . strtoupper ( $hex )):( strtoupper ( $hex )));
>
$out = str_replace ( ‘+’ , ‘%20’ , $out );
$out = str_replace ( ‘_’ , ‘%5F’ , $out );
$out = str_replace ( ‘.’ , ‘%2E’ , $out );
$out = str_replace ( ‘-‘ , ‘%2D’ , $out );
return $out ;
>
?>

It can be fully decoded using the unscape function in Javascript.

14 years ago

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

9 years ago

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 :

«html»:[
«type»:»p»,
«html»:»Patient Record»
>,
«name»:»patient.name.first»,
«id»:»txt-patient.name.first»,
«caption»:»first name»,
«type»:»text»,
>,

«name»:»patient.name.last»,
«id»:»txt-patient.name.last»,
«caption»:»last name»,
«type»:»text»,
>,
«type» : «submit»,
>

//get the json source code from the mongodb
$jsonform = urlencode ( $this -> data [ ‘Post’ ][ ‘jsonform’ ]);

// passing the variable fro PHP to javascript
var thejsonform default»> «;

//var fname = $(‘input#fname’).val();
var dataString = «jsonform POST»,
// url: «test1.php»,
data: dataString,
success: function()
2 months ago

this function will encode the URL while preserving the functionality of URL so you can copy and paste it in the browser
«`
function urlEncode($url) $parsedUrl = parse_url($url);

$encodedScheme = urlencode($parsedUrl[‘scheme’]);
$encodedHost = urlencode($parsedUrl[‘host’]);

$encodedPath = implode(‘/’, array_map(‘urlencode’, explode(‘/’, $parsedUrl[‘path’])));
if (isset($parsedUrl[‘query’])) $encodedQuery = ‘?’ . urlencode($parsedUrl[‘query’]);
> else $encodedQuery = »;
>

16 years ago

Like «Benjamin dot Bruno at web dot de» earlier has writen, you can have problems with encode strings with special characters to flash. Benjamin write that:

function flash_encode ( $input )
return rawurlencode ( utf8_encode ( $input ));
>
?>

. could do the problem. Unfortunately flash still have problems with read some quotations, but with this one:

function flash_encode ( $string )
$string = rawurlencode ( utf8_encode ( $string ));

$string = str_replace ( «%C2%96» , «-» , $string );
$string = str_replace ( «%C2%91» , «%27» , $string );
$string = str_replace ( «%C2%92» , «%27» , $string );
$string = str_replace ( «%C2%82» , «%27» , $string );
$string = str_replace ( «%C2%93» , «%22» , $string );
$string = str_replace ( «%C2%94» , «%22» , $string );
$string = str_replace ( «%C2%84» , «%22» , $string );
$string = str_replace ( «%C2%8B» , «%C2%AB» , $string );
$string = str_replace ( «%C2%9B» , «%C2%BB» , $string );

return $string ;
>
?>

. should solve this problem.

5 years ago

Keep in mind that, if you prepare URL for a connection and used the urlencode on some parameters and didn’t use it on the rest of parameters, it will not be decoded automatically at the destination position if the not encoded parameters have special characters that urlencode encodes it.

here is the second parameter has spaces which urlencode converts it to (+).

after using this URL, the server will discover that the second parameter has not been encoded , then the server will not decode it automatically.

this took more than 2 hours to be discovered and hope to save your time.

8 years ago

Since PHP 5.3.0, urlencode and rawurlencode also differ in that rawurlencode does not encode ~ (tilde), while urlencode does.

17 years ago

Apache’s mod_rewrite and mod_proxy are unable to handle urlencoded URLs properly — http://issues.apache.org/bugzilla/show_bug.cgi?id=34602

If you need to use any of these modules and handle paths that contain %2F or %3A (and few other encoded special url characters), you’ll have use a different encoding scheme.

My solution is to replace «%» with «‘».
function urlencode ( $u )
return str_replace (array( «‘» , ‘%’ ),array( ‘%27’ , «‘» ), urlencode ( $u ));
>

function urldecode ( $u )
return urldecode ( strtr ( $u , «‘» , ‘%’ ));
>
?>

13 years ago

I wrote this simple function that creates a GET query (for URLS) from an array:

function encode_array ( $args )
if(! is_array ( $args )) return false ;
$c = 0 ;
$out = » ;
foreach( $args as $name => $value )
if( $c ++ != 0 ) $out .= ‘&’ ;
$out .= urlencode ( » $name » ). ‘=’ ;
if( is_array ( $value ))
$out .= urlencode ( serialize ( $value ));
>else $out .= urlencode ( » $value » );
>
>
return $out . «\n» ;
>
?>

If there are arrays within the $args array, they will be serialized before being urlencoded.

Some examples:
echo encode_array (array( ‘foo’ => ‘bar’ )); // foo=bar
echo encode_array (array( ‘foo&bar’ => ‘some=weird/value’ )); // foo%26bar=some%3Dweird%2Fvalue
echo encode_array (array( ‘foo’ => 1 , ‘bar’ => ‘two’ )); // foo=1&bar=two
echo encode_array (array( ‘args’ => array( ‘key’ => ‘value’ ))); // args=a%3A1%3A%7Bs%3A3%3A%22key%22%3Bs%3A5%3A%22value%22%3B%7D
?>

2 years ago

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.

18 years ago

Do not let the browser auto encode an invalid URL. Not all browsers perform the same encodeing. Keep it cross browser do it server side.

15 years ago

I’m running PHP version 5.0.5 and urlencode() doesn’t seem to encode the «#» character, although the function’s description says it encodes «all non-alphanumeric» characters. This was a particular problem for me when trying to open local files with a «#» in the filename as Firefox will interpret this as an anchor target (for better or worse). It seems a manual str_replace is required unless this was fixed in a future PHP version.

$str = str_replace(«#», «%23», $str);

19 years ago

Be careful when encoding strings that came from simplexml in PHP 5. If you try to urlencode a simplexml object, the script tanks.

I got around the problem by using a cast.

$newValue = urlencode( (string) $oldValue );

16 years ago

kL’s example is very bugged since it loops itself and the encode function is two-way.

Why do you replace all %27 through ‘ in the same string in that you replace all ‘ through %27?

Lets say I have a string: Hello %27World%27. It’s a nice day.
I get: Hello Hello ‘World’. It%27s a nice day.

With other words that solution is pretty useless.

Solution:
Just replace ‘ through %27 when encoding
Just replace %27 through ‘ when decoding. Or just use url_decode.

3 years ago

I think the description does not exactly match what the function does:

Returns a string in which all non-alphanumeric characters
except -_. have been replaced with a percent (%) sign followed
by two hex digits and spaces encoded as plus (+) signs.

urlencode(‘ö’) gives me ‘%C3%B6’. So more then just a percent sign followed by two hex digits.

4 years ago

urlencode corresponds to the definition for application/x-www-form-urlencoded in RFC 1866 (https://tools.ietf.org/html/rfc1866#section-8.2.1), and not for url encoded parts in URI. Use only rawurlencode for encode raw URI parts (e.g. query/search part)!

19 years ago

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.

$url = «index.php?id=4&pg=2» ;
$url = urlencode ( urlencode ( $url ));

echo «» ;
?>

On the page being opened by the javascript function (page.php), you only need to urldecode() once, because when javascript ‘touches’ the url that passes through it, it decodes the url once itself. So, just decode it once more in your PHP script to fully undo the double-encoding.

$url = urldecode ( $_GET [ ‘url’ ]);
?>

If you don’t do this, you’ll find that the result url value in the target script is missing all the var=values following the ? question mark.

15 years ago

When using XMLHttpRequest or another AJAX technique to submit data to a PHP script using GET (or POST with content-type header set to ‘x-www-form-urlencoded’) you must urlencode your data before you upload it. (In fact, if you don’t urlencode POST data MS Internet Explorer may pop a «syntax error» dialog when you call XMLHttpRequest.send().) But, you can’t call PHP’s urlencode() function in Javascript! In fact, NO native Javascript function will urlencode data correctly for form submission. So here is a function to do the job fairly efficiently:

// PHP-compatible urlencode() for Javascript
function urlencode(s) s = encodeURIComponent(s);
return s.replace(/~/g,’%7E’).replace(/%20/g,’+’);
>

// sample usage: suppose form has text input fields for
// country, postcode, and city with and so-on.
// We’ll use GET to send values of country and postcode
// to «city_lookup.php» asynchronously, then update city
// field in form with the reply (from database lookup)

function lookup_city() var elm_country = document.getElementById(‘country’);
var elm_zip = document.getElementById(‘postcode’);
var elm_city = document.getElementById(‘city’);
var qry = ‘?country=’ + urlencode(elm_country.value) +
‘&postcode=’ + urlencode(elm_zip.value);
var xhr;
try xhr = new XMLHttpRequest(); // recent browsers
> catch (e) alert(‘No XMLHttpRequest!’);
return;
>
xhr.open(‘GET’,(‘city_lookup.php’+qry),true);
xhr.onreadystatechange = function() if ((xhr.readyState != 4) || (xhr.status != 200)) return;
elm_city.value = xhr.responseText;
>
xhr.send(null);
>

17 years ago

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

/* Makes an valid html request url by parsing the params array
* @param $params The parameters to be converted into URL with key as name.
*/
function MakeRequestUrl($params)
$querystring=null;
foreach ($params as $name => $value)
$querystring=$name.’=’.urlencode($value).’&’.$querystring;
>
// Cut the last ‘&’
$querystring=substr($querystring,0,strlen($querystring)-1);
return htmlentities($querystring);
>

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

18 years ago

I was testing my input sanitation with some strange character entities. Ones like ? and ? were passed correctly and were in their raw form when I passed them through without any filtering.

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.

PS: If you try copy/pasting one of these characters to a TXT file, it will translate to a ?.

9 years ago

Example:
.htaccess
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^test-(.*)$ index.php?token=$1

index.php
var_dump ( $_GET );

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-3test-bla-bla-4%253E2-y-3%253C6

the problem is that the characters are decoded 2 times, 1 single, the first time mod_rewrite, the second is to create the php $ _GET array.

also, you can use this technique to the same as the complex functions of other notes.

2 years ago

Стань королем настоящего средневекового королевства!
Захватывающая RPG игра и симулятор замка
https://fas.st/tdhru

18 years ago

Constructing hyperlinks safely HOW-TO:

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

echo ‘, htmlspecialchars ( $url ), ‘»>’ , htmlspecialchars ( $link_label ), » ;
?>

This example covers all the encodings you need to apply in order to create URLs safely without problems with any special characters. It is stunning how many people make mistakes with this.

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

10 years ago

Simple static class for array URL encoding

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

/** Main encoding worker
* @param string $perfix
* @param array $array
* @param string $ret byref Push record to return array
* @param mixed $fe Is first call to function?
*/
private static function encode_part ( $perfix , $array , & $ret , $fe = false )
foreach ( $array as $k => $v )
switch ( gettype ( $v ))
case ‘float’ :
case ‘integer’ :
case ‘string’ : $ret [ $fe ? $k : $perfix . ‘[‘ . $k . ‘]’ ] = $v ; break;
case ‘boolean’ : $ret [ $fe ? $k : $perfix . ‘[‘ . $k . ‘]’ ] = ( $v ? ‘1’ : ‘0’ ); break;
case ‘null’ : $ret [ $fe ? $k : $perfix . ‘[‘ . $k . ‘]’ ] = ‘NULL’ ; break;
case ‘object’ : $v = (array) $v ;
case ‘array’ : self :: encode_part ( $fe ? $perfix . $k : $perfix . ‘[‘ . $k . ‘]’ , $v , $ret , false ); break;
>
>
>

/** UrlEncode Array
* @param mixed $array Array or stdClass to encode
* @returns string Strings ready for send as ‘application/x-www-form-urlencoded’
*/
public static function go ( $array )
$buff = array();
if ( gettype ( $array ) == ‘object’ ) $array = (array) $array ;
self :: encode_part ( » , $array , $buff , true );
$retn = » ;
foreach ( $buff as $k => $v )
$retn .= urlencode ( $k ) . ‘=’ . urlencode ( $v ) . ‘&’ ;
return $retn ;
>
>

$buffer = array(
‘master’ => ‘master.zenith.lv’ ,
‘join’ =>array( ‘slave’ => ‘slave1.zenith.lv’ , ‘slave2’ =>array( ‘node1.slave2.zenith.lv’ , ‘slave2.zenith.lv’ )),
‘config’ => new stdClass ()
);
$buffer [ ‘config’ ]-> MaxServerLoad = 200 ;
$buffer [ ‘config’ ]-> MaxSlaveLoad = 100 ;
$buffer [ ‘config’ ]-> DropUserNoWait = true ;

$buffer = urlencode_array :: go ( $buffer );
parse_str ( $buffer , $data_decoded );

header ( ‘Content-Type: text/plain; charset=utf-8’ );
echo ‘Encoded String :’ . str_repeat ( ‘-‘ , 80 ) . «\n» ;
echo $buffer ;
echo str_repeat ( «\n» , 3 ) . ‘Decoded String byPhp :’ . str_repeat ( ‘-‘ , 80 ) . «\n» ;
print_r ( $data_decoded );

  • Copyright © 2001-2023 The PHP Group
  • My PHP.net
  • Contact
  • Other PHP.net sites
  • Privacy policy

Что за символы?

Здравствуйте. Есть у меня такая строка «%D0%93%D0%BE%D0%BC%D0%B5» знаю что здесь написано Гомель, как можно перевести нормальные буквы utf-8 в это? И что это вообще такое?

  • Вопрос задан более трёх лет назад
  • 851 просмотр

Комментировать
Решения вопроса 2
Помог? — «Отметить решением»
Такое кодирование применяется, чаще всего, в url

echo urldecode( '%D0%93%D0%BE%D0%BC%D0%B5' ); // Гоме echo urlencode( 'Гомель' ); // %D0%93%D0%BE%D0%BC%D0%B5%D0%BB%D1%8C

Подробнее можно посмотреть здесь

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

// http%3A%2F%2Fexample.com%2Findex-2.php $url = urlencode( 'http://example.com/index-2.php' ); // http://example.com/index.php?url=http%3A%2F%2Fexample.com%2Findex-2.php echo 'http://example.com/index.php?url=' . $url;

Ответ написан более трёх лет назад
Комментировать
Нравится 1 Комментировать

secsite

Безопасные и быстрые сайты

И что это вообще такое?

Стандарт URL использует набор символов US-ASCII. Это имеет серьёзный недостаток, поскольку разрешается использовать лишь латинские буквы, цифры и несколько знаков пунктуации. Все другие символы необходимо перекодировать. Например, перекодироваться должны буквы кириллицы, буквы с диакритическими знаками, лигатуры, иероглифы. Перекодирующая кодировка описана в стандарте RFC 3986 и называется URL-encoding, URLencoded или percent‐encoding.

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

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