Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg

PHP : Function Reference : URL Functions : urlencode


URL-encodes string (PHP 4, PHP 5)
string urlencode ( string str )

Example 2577. urlencode() example

echo '<a href="mycgi?foo=', urlencode($userinput), '">';

Example 2578. urlencode() and htmlentities() example

= 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
'<a href="mycgi?' . htmlentities($query_string) . '">';

Related Examples ( Source code ) » urlencode

Code Examples / Notes » urlencode

What I use instead:
function escape($url)
return str_replace("%2F", "/", urlencode($url));


Try this one out live:


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 &amp;.
 $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)
   foreach ($params as $name => $value)
  // Cut the last '&'
  return htmlentities($querystring);
 Will output: action=sell%26buy&amp;name=tore


The information on this page is misleading in that you might think the ampersand (&) will only need to be escaped as &amp; when there is ambiguity with an existing character entity. This is false; the W3C page linked to from here clarifies that the ampersands must ALWAYS be escaped.
The following:
 <a href='/script.php?variable1=value1&variable2=value2'>Link</a>
is INVALID HTML. It needs to be written as:
 <a href='/script.php?variable1=value1&amp;variable2=value2'>Link</a>
in order for the link to go to:
I applaud the W3C's recommendation to use semicolons (';') instead of the ampersands, but it doesn't really change the fact that you still need to HTML-escape the value of all your HTML tag attributes. The following:
 <span title='Rose & Mary'>Some text</span>
is also INVALID HTML. It needs to be escaped as:
 <span title='Rose &amp; Mary'>Some text</span>


Reply to 'peter at mailinator dot com'
If you are having problems using urldecode in PHP following the escape() function in Javascript, try to do a decodeURI() before the escape(). This fixed it for me at least.


quote: "Apache's mod_rewrite and mod_proxy are unable to handle urlencoded URLs properly -"
The most simple solution is to use urlencode twice!
echo urlencode(urlencode($var));
Apache's mod_rewrite will handle it like a normal string using urlencode once.


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.

in reply to "kl"

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.
Just replace ' through %27 when encoding
Just replace %27 through ' when decoding. Or just use url_decode.


Just remember that according to W3C standards, you must rawurlencode() the link that's provided at the end of a mailto.
<a href=" testing(s)&">Mail Me</a>
Needs to be escaped (which rawurlencode() does for us).
The colon is OK after "mailto", as is the "@" after the e-mail name.
However, the rest of the URL needs to be encoded, replacing the following:
'?' => %3F
'=' => %3D
' ' => %20
'(' => %28
')' => %29
'&' => %26
'@' => %40 (note this one is in ''
I tried to post the note with the correct text (that is the characters replaced in the note), but it said that there was a line that was too long, and so wouldn't let me add the note.
As a secondary note, I noticed that the auto-conversion routines at this site itself stopped the link at the space after "Simple testing(s)' in the first entry shown above.


Just a simple comment, really, but if you need to encode apostrophes, you should be using rawurlencode as opposed to just urlencode.
Naturally, I figured that out the hard way.

php dot net

In AJAX era you might need to use UCS-2 (UTF-16) url-encoding (chars represented in form '%uXXXX' - e.g. '%u043e' for Russian 'o'). But PHP is weak in working with multibyte encoded strings, so you cannot simply use urlencode() for the string in UCS-2. Here is simple function serving for this purpose.
Note, that this function takes UTF8-encoded string as input and, then, for internal purposes use some 1-byte encoding (cp1251 in my case). If you have the string in some 1-byte encoding, you may remove the first iconv() and modify the second one and thus slightly simplify the function.
function utf16urlencode($str)
$str = iconv("utf-8", "cp1251", $str);
$res = "";
for ($i = 0; $i < strlen($str); $i++) {
$res .= "%u";
$a = iconv("cp1251", "ucs-2", $str[$i]);
for ($j = 0; $j < strlen($a); $j++) {
$n = dechex(ord($a[$j]));
if (strlen($n) == 1) {
$n = "0$n";
$res .= $n;
return $res;


If you want to pass a url with parameters as a value IN a url AND through a javascript function, such as...
  <a href="javascript:openWin('page.php?url=index.php?id=4&pg=2');">
...pass the url value through the PHP urlencode() function twice, like this...
  $url = "index.php?id=4&pg=2";
  $url = urlencode(urlencode($url));
  echo "<a href=\"javascript:openWin('page.php?url=$url');\">";
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...

benjamin dot bruno

If you need to prepare strings with special characters (like German Umlaut characters) in order to import them into flash files via GET, try using utf8_encode and rawurlencode sequentially, like this:
function flash_encode ($input) {
 return rawurlencode(utf8_encode($input));
Thus, you can avoid having use encodeURI in JavaScript, which is only availabe in JavaScript 1.5.


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): &#8252; &#9616; &#9488;and &#920; 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 ?.


I think this was mentioned earlier but it was confusing.. But I had some problems with the urlencode eating my '/' so I did a simple str_replace like the following:
$url = urlencode($img);
$img2 = "$url";
$img2 = str_replace('%2F54', '/', $img2);
$img2 = str_replace('+' , '%20' , $img2);
You don't need to replace the '+' but I just feel comfortable with my %20, although it may present a problem if whatever you're using the str_replace for has a '+' in it where it shouldn't be.
But that fixed my problem.. all the other encodes like htmlentities and rawurlencode just ate my /'s


I rewrote inus at flowingcreativity dot net function to generate an encoded url string from the POST, or GET array. It handles properly POST/GET array vars.
function _HTTPRequestToString($arr_request, $var_name, $separator='&') {
$ret = "";
if (is_array($arr_request)) {
foreach ($arr_request as $key => $value) {
if (is_array($value)) {
if ($var_name) {
$ret .= $this->_HTTPRequestToString($value, "{$var_name}[{$key}]", $separator);
} else {
$ret .= $this->_HTTPRequestToString($value, "{$key}", $separator);
} else {
if ($var_name) {
$ret .= "{$var_name}[{$key}]=".urlencode($value)."&";
} else {
$ret .= "{$key}=".urlencode($value)."&";
if (!$var_name) {
$ret = substr($ret,0,-1);
return $ret;


I just came across the need for a function that exports an array into a query string. Being able to use urlencode($theArray) would be nice, but here's what I came up with:
function urlencode_array(
$var, // the array value
$varName, // variable name to be used in the query string
$separator = '&' // what separating character to use in the query string
) {
$toImplode = array();
foreach ($var as $key => $value) {
if (is_array($value)) {
$toImplode[] = urlencode_array($value, "{$varName}[{$key}]", $separator);
} else {
$toImplode[] = "{$varName}[{$key}]=".urlencode($value);
return implode($separator, $toImplode);
This function supports n-dimensional arrays (it encodes recursively).


I had difficulties with all above solutions. So I applied a dirty simple solution by using:
The string's length is a bit longer but no more problem with encoding.

r mortimer

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.


Diferrent from the above example you do not have to encode URLs in hrefs with this. The browser does it automaticaly, so you just have to encode it with htmlentities() ;)


Constructing hyperlinks safely HOW-TO:
$path_component = 'machine/generated/part';
$url_parameter1 = 'this is a string';
$url_parameter2 = 'special/weird "$characters"';
$url = ''. rawurlencode($path_component) . '?param1=' . urlencode($url_parameter1) . '&param2=' . urlencode($url_parameter2);
$link_label = "Click here & you'll be <happy>";
echo '<a href="', htmlspecialchars($url), '">', htmlspecialchars($link_label), '</a>';
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.
- 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.


Be carefull when using this function with JavaScript escape function.
In JavaScript when you try to encode utf-8 data with escape function you will get some strange encoded string which you wont be able to decode with php url(de)encode funtions.
I found a website which has some very good tool regarding this problem:
It has components which deal with url (en)decode.


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


Apache's mod_rewrite and mod_proxy are unable to handle urlencoded URLs properly -
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,"'",'%'));


Another thing to keep in mind is that urlencode is not unicode.
For example, urlencoding enquête from an UTF-8 project will produce enqu%C3%AAte.
However, urlencode(utf8_decode('enquête')) produces enqu%EAte, like expected.

php dot net

Addition to the previous note:
to make it work on *nix systems (where big-endian byte order in UTF-16 is being used, in contrast to WIN32) add following lines right after the second iconv():
if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
$b = $a;
$a[1] = $b[0];
$a[0] = $b[1];


---[ Editor's Note ]---
You can also use rawurlencode() here, and skip the functions provided in this note.
---[ /Editor's Nore]---
For handling slashes in redirections, (see comment from cameron at enprises dot com), try this :
function myurlencode ( $TheVal )
return urlencode (str_replace("/","%2f",$TheVal));
function myurldecode ( $TheVal )
return str_replace("%2f","/",urldecode ($TheVal));
This is effectively a double urlencode for slashes and single urlencode for everything else.  So, it is more "standardised" than his suggestion of using a + sign, and more readable (and search engine indexable) than a full double encode/decode.

roamy: info

<?// urlencode + urldecode 4 Linux/Unix-Servers:=============
//=====This small script matches all encoded String for ========
//=====Linux/Unix-Servers For IIS it got to be  The Other Way  ==
//===== around...and remember in a propper Url =============
//===== there shoudn't be the 'dirty Letter': %C3==============
function int2hex($intega){
$Ziffer = "0123456789ABCDEF";
return $Ziffer[($intega%256)/16].$Ziffer[$intega%16];
function url_decode($text){
$in = "%".int2hex($i);
$out = "%C3%".int2hex($i-64);
$text = str_replace($in,$out,$text);
return urldecode($text);
function url_encode($text){
$text = urlencode($text);
$in = "%".int2hex($i);
$out = "%C3%".int2hex($i-64);
$text = str_replace($in,$out,$text);
return $text;

Change Language

Follow Navioo On Twitter
eXTReMe Tracker