Urlencode не работает php

Urlencode не работает php

БлогNot. PHP: urlencode и urldecode — что нужно для скриптов в однобайтовой кодировке

PHP: urlencode и urldecode — что нужно для скриптов в однобайтовой кодировке

Распространённая у новичков проблема — функции urlencode и urldecode работают «неожиданно», если кодировка — не UTF-8.

Да, с одной стороны urldecode должна думать, что её аргумент в UTF-8:

data should first be encoded as octets according to the UTF-8 character encoding
отсюда

Поэтому, делая всё в однобайтовой кодировке, например, Windows-1251, мы рискуем увидеть на выходе юникодовские «кракозябры»:

Здесь строка получена параметром URL и скрипт под именем script.php вызван из корневой папки локалхоста запросом

В данном случае браузер получает строку «как есть», в нём при этом выставлена кодировка Windows-1251 и в Denwer тоже.

Если передать скрипту уже URL-кодированный однобайтовым кодом «привет» запросом

то всё, конечно, напечатается нормально. А вот для «двухбайтового» URL-запроса

скрипт опять покажет «кракозябры» на странице и правильный «привет» в адресной строке — кодировка-то у нас всюду однобайтовая 🙂 В общем, если входная кодировка другая, чем Юникод, решением проблемы будет iconv.

Так, показать URL-кодированную запись переданного через URL «привета» и сам исходный «привет» можно в виде

(показано только содержимое тега ). Как видим, переменные адресной строки браузера предполагаются заданными в Юникоде, даже если на локалхосте и в коде страницы указана другая кодировка.

Если сам файл со скриптом тоже в кодировке Windows-1251 и переменная $q задана непосредственно в скрипте (или прочитана из файла, базы данных в той же кодировке), её декодировать не нужно:

Обратите внимание, что из-за однобайтовой кодировки в данном случае получатся не юникодовские «октеты», а нормальные байты. Преобразование будет обратимо и в однобайтовой кодировке:

Источник

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

(PHP 4, PHP 5, PHP 7)

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

Описание

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

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

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

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

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

Примеры

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

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

Примечания

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

PHP поддерживает изменение разделителя аргументов на рекомендуемый W3C символ «точку с запятой» путём изменения директивы arg_separator в .ini файле. К сожалению, большинство пользовательских приложений не отправляют данные формы в формате с разделителем «точка с запятой». Более переносимый способ решить эту проблему — это использовать & вместо & в качестве разделителя. Вам не нужно будет для этого изменять PHP-директиву arg_separator. Оставьте разделитель как &, но кодируйте ваши URL с помощью htmlentities() или htmlspecialchars() .

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

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

Источник

urlencode

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

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

Описание

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

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

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

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

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

Примеры

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

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

Примечания

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

PHP поддерживает изменение разделителя аргументов на рекомендуемый W3C символ «точку с запятой» путём изменения директивы arg_separator в .ini файле. К сожалению, большинство пользовательских приложений не отправляют данные формы в формате с разделителем «точка с запятой». Более переносимый способ решить эту проблему — это использовать & вместо & в качестве разделителя. Вам не нужно будет для этого изменять PHP-директиву arg_separator. Оставьте разделитель как &, но кодируйте ваши URL с помощью htmlentities() или htmlspecialchars() .

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

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

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.

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( ‘!’ , ‘*’ , «‘» , «(» , «)» , «;» , «:» , «@» , «&» , «=» , «+» , «$» , «,» , «/» , «?» , «%» , «#» , «[» , «]» );
return str_replace ( $entities , $replacements , urlencode ( $string ));
>
?>

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

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:

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.

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 :

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

?>
//AJAX SUBMIT FORM

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.

= «index.php?id=4&pg=2» ;
$url = urlencode ( urlencode ( $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.

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

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

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

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 rawurlencode for parts that come before «?».
— Use htmlspecialchars for HTML tag parameters and HTML text content.

if you have a url like this: test-blablabla-4>3-y-3 ( $_GET );

$foo = ‘test-bla-bla-4>2-y-3 ;
$foo_encoded = urlencode ( urlencode ( $foo ));
?>
; ?> «> ; ?>

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
<

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

Источник

Substituting whitespaces with %20 in PHP. urlencode and rawurlencode does not work

I’m trying to constitute a URL from a multi-word string: so I have

and I ‘m trying to get :

but I could not do it with PHP.

how can I get «my%20string» ?

Thanks for any help !

Maybe I can do str_replace(urlencode(),etc); but is there an argument for urlencode so that it converts correctly by itself?

Turns out that, as Amal Murali said, rawurlencode() WAS doing it, I just didn’t see it on the browser, when I hover on the link with my mouse.

But when I check the source code, or click on the link, I see that rawurlencode(); produces the correct link. (With %20 ‘s.).

3 Answers 3

rawurlencode() is what you’re looking for. However, if your Content-Type is set to text/html (which is the default), then you will see the space character instead of the encoded entity.

Note: I’m not suggesting that you should change the Content-Type header in your original script. It’s just to show that your rawurlencode() call is working and to explain why you’re not seeing it.

I layed it out that way to present each step, but I’d just write a method / function for it.

Actually, given that it is standard now to use «_» or «-» in place of spaces for SEO purposes, I’d just replace %20 with _ or —

Let me know if that helps.

If you want to see %20 in your URLs you must use rawurlencode().

You should not mess with the content type, because you risk seeing some browsers getting confused and serving your HTML pages as text (as source), that is with the tags not being interpreted into a proper web page.

Of course if you want to debug your PHP code by outputting the %20 , you are not going to really see a visible result as the text/html encoding will tell your browser to interpret the codes and thus your %20 will transparently be converted into a space.

The «use plain/text» suggestion is just for debugging purposes so you can really see the %20 being generated. You will use it to create URLs anyway, so the whole plain vs html encoding won’t apply to you.

Источник

Читайте также:  Почему не работает доводчик стекла
Оцените статью