urlencode

(PHP 4, PHP 5)

urlencodeURL-encodes string

Description

string urlencode ( string $str )

This function is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.

Parameters

str

The string to be encoded.

Return Values

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. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. This differs from the » RFC 3986 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs.

Examples

Example #1 urlencode() example

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

Example #2 urlencode() and htmlentities() example

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

Notes

Note:

Be careful about variables that may match HTML entities. Things like &amp, &copy and &pound are parsed by the browser and the actual entity is used instead of the desired variable name. This is an obvious hassle that the W3C has been telling people about for years. The reference is here: » http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2.

PHP supports changing the argument separator to the W3C-suggested semi-colon through the arg_separator .ini directive. Unfortunately most user agents do not send form data in this semi-colon separated format. A more portable way around this is to use &amp; instead of & as the separator. You don't need to change PHP's arg_separator for this. Leave it as &, but simply encode your URLs using htmlentities() or htmlspecialchars().

See Also

Коментарии

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 );
2004-09-17 16:51:37
http://php5.kiev.ua/manual/ru/function.urlencode.html
Автор:
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.
2005-08-26 04:14:53
http://php5.kiev.ua/manual/ru/function.urlencode.html
Автор:
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 "'".
<?php
function urlencode($u)
{
    return 
str_replace(array("'",'%'),array('%27',"'"),urlencode($u));
}

function 
urldecode($u)
{
    return 
urldecode(strtr($u,"'",'%'));
}
?>
2006-09-06 20:13:50
http://php5.kiev.ua/manual/ru/function.urlencode.html
Автор:
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.
2007-02-20 03:23:03
http://php5.kiev.ua/manual/ru/function.urlencode.html
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:

<?php
   
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:

<?php
   
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.
2007-08-04 20:04:51
http://php5.kiev.ua/manual/ru/function.urlencode.html
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.

Example:

$str = str_replace("#", "%23", $str);
2008-08-12 20:12:16
http://php5.kiev.ua/manual/ru/function.urlencode.html
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().
2009-06-29 10:24:10
http://php5.kiev.ua/manual/ru/function.urlencode.html
I needed encoding and decoding for UTF8 urls, I came up with these very simple fuctions. Hope this helps!

<?php
   
function url_encode($string){
        return 
urlencode(utf8_encode($string));
    }
   
    function 
url_decode($string){
        return 
utf8_decode(urldecode($string));
    }
?>
2009-07-23 13:44:44
http://php5.kiev.ua/manual/ru/function.urlencode.html
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:

<?php
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.
2010-02-24 13:17:50
http://php5.kiev.ua/manual/ru/function.urlencode.html
I wrote this simple function that creates a GET query (for URLS) from an array:

<?php
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:
<?php
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
?>
2010-04-07 11:48:38
http://php5.kiev.ua/manual/ru/function.urlencode.html
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.

<?php
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$replacementsurlencode($string));
}
?>
2010-05-18 21:53:57
http://php5.kiev.ua/manual/ru/function.urlencode.html
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 :

<script type="text/javascript">
$(function() {
      // Generate a form using jquery.dfrom
        $("#myform").dform({
                       
        "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",
              }
           
        ]
    });
    });
</script>
<form id="myform">

<?php
//get the json source code from the mongodb
$jsonformurlencode($this->data['Post']['jsonform']);

?>
//AJAX SUBMIT FORM
<script type="text/javascript">
$('#myform').submit(function(){
 
               
    //    passing the variable fro PHP to javascript   
        var thejsonform="<?php echo $jsonform ?>";

  //var fname = $('input#fname').val();
  var dataString = "jsonform=" + thejsonform ; 

    $.ajax({
          type: "POST",
        //  url: "test1.php",
          data: dataString,
          success: function() {
           
          }
         }); 
 

return false;
});
2013-11-06 09:33:04
http://php5.kiev.ua/manual/ru/function.urlencode.html
Since PHP 5.3.0, urlencode and rawurlencode also differ in that rawurlencode does not encode ~ (tilde), while urlencode does.
2014-12-10 20:52:00
http://php5.kiev.ua/manual/ru/function.urlencode.html
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.

example :

$xml = simplexml_load_file("http://www.testing.com?me=test&first=".urlencode('dummy string')."&second=here is the string");

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.
2018-02-26 12:22:57
http://php5.kiev.ua/manual/ru/function.urlencode.html
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)!
2019-09-20 21:12:36
http://php5.kiev.ua/manual/ru/function.urlencode.html
Автор:
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.
2020-01-16 14:00:03
http://php5.kiev.ua/manual/ru/function.urlencode.html
Автор:
Стань королем настоящего средневекового королевства! 
Захватывающая RPG игра и симулятор замка 
https://fas.st/tdhru
2021-09-11 01:58:24
http://php5.kiev.ua/manual/ru/function.urlencode.html
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 = '';
    }
   
    return "{$encodedScheme}://{$encodedHost}{$encodedPath}{$encodedQuery}";
}
```
2023-08-29 03:31:03
http://php5.kiev.ua/manual/ru/function.urlencode.html

    Поддержать сайт на родительском проекте КГБ