How to Properly Url Encode a String in PHP

How to properly URL encode a string in PHP?

For the URI query use urlencode/urldecode; for anything else use rawurlencode/rawurldecode.

The difference between urlencode and rawurlencode is that

  • urlencode encodes according to application/x-www-form-urlencoded (space is encoded with +) while
  • rawurlencode encodes according to the plain Percent-Encoding (space is encoded with %20).

PHP urlencode converting HTML special characters

Your original data probably includes the HTML character reference for '

When you print_r it, your browser interprets it as HTML and renders a '.

PHP urlencode issue with a parameter in my string: ¬ify_url incorrectly returns ¬ify_url

urlencode does not usually replace ¬ at all, but does replace & with %26. See example here: http://sandbox.onlinephpfunctions.com/code/e9d62797d01f8162170e5ad5181e14fc339faa52

You could try replacing & with %26 before urlencode.

$urlString = str_replace('&', '%26', $urlString);

How do I get PHP to properly URL encode a numerically indexed array?

You were close at second attempt:

$data = array(58,17);
//equivalent to $string = 'data%5B0%5D=58&data%5B1%5D=17';
$string = http_build_query(array('data' => $data));

You could strip those numeric indexes with preg_replace, but I would try if it changes anything first.

Urlencode everything but slashes?

  1. Split by /
  2. urlencode() each part
  3. Join with /

URL encoding in PHP

The browser will urlencode them for you. Go to google and search for "&", and you'll see "q=%26" in the URL.

PHP URL Encoding / Decoding

The weird characters in the values passed in the URL should be escaped, using urlencode().



For example, the following portion of code :

echo urlencode('dsf13f3343f23/23=');

would give you :

dsf13f3343f23%2F23%3D

Which works fine, as an URL parameter.



And if you want to build aquery string with several parameters, take a look at the http_build_query() function.

For example :

echo http_build_query(array(
'id' => 'dsf13f3343f23/23=',
'a' => 'plop',
'b' => '$^@test',
));

will give you :

id=dsf13f3343f23%2F23%3D&a=plop&b=%24%5E%40test

This function deals with escaping and concatenating the parameters itself ;-)

PHP urlencode for chinese characters

You're URLencoding using the charset you specify in your header. %D0%C2 is 新 in gb2312; %E6%96%B0 is 新 in UTF-8. Switch your charset over to UTF-8 and you should fix this issue and still be able to display Simplified Chinese Han.



Related Topics



Leave a reply



Submit