How To Encode URI Data In Popular Languages

pradeep's Avatar author of How To Encode URI Data In Popular Languages
This is an article on How To Encode URI Data In Popular Languages in Web Development.
URL Encoding also known as Percent-encoding is the way to encode data passed in an URI (Uniform Resource Identifier), this system is used to convert special characters to hex form prefixed with a % sign, and prevents broken URLs. An encoded URL will look like the following:

Code:
http://www.google.com/search?q=%26pradeep+]%3D

In this article we'll see how URL encoding can be done in different languages:

PHP



PHP comes with a built-in function urlencode which Percent-encodes the string passed to it.

Code: PHP
<?php
print '<a href="/script/home.php?user_input=', urlencode($user_input), '">User Input</a>';
?>

Perl



In Perl there are multiple modules available which can do the work for you, or you can write such a subroutine yourself, let's take a look at booth examples below:

Code: Perl
use URI::Escape;

$url = sprintf('http://pradeep.net.in/cgi-bin/hello.pl?user_input=%s',uri_escape($user_input));

sub urlencode {
    my $s = shift;
    $s =~ s/ /+/g;
    $s =~ s/([^A-Za-z0-9\+-])/sprintf("%%%02X", ord($1))/seg;
    return $s;
}

$url = sprintf('http://pradeep.net.in/cgi-bin/hello.pl?user_input=%s',urlencode($user_input));

Python



In Python the urllib module is used:

Code: Python
import urllib

print "Url : http://pradeep.net.in/cgi-bin/hello.py?user_input=%s" % (urllib.quote_plus(user_input))

JavaScript



The built-in functions encodeURIComponent(str) and encodeURI(str)

Code: JavaScript
var url = "http://pradeep.net.in/cgi-bin/hello.py?user_input=" + encodeURIComponent(user_input);

ASP.Net



ASP.Net also has a built-in function to encode URL components with special characters.

Code: C#
String sUrl;
sUrl = "http://pradeep.net.in/cgi-bin/hello.py?user_input=" + Server.UrlEncode(sUserInput);

Response.Write("<a href=" + sUrl + ">User Input</a>");

References



mark.stosberg.com
Wiki
Stackoverflow
Banned
2Sep2012,08:07   #2
vaayaaedu's Avatar
great reference. I was looking for URL encode in ASP