How To Encode URI Data In Popular Languages

Discussion in 'Web Development' started by pradeep, Jul 27, 2012.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    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.

    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:
    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:
    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:
    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:
    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
     
  2. vaayaaedu

    vaayaaedu Banned

    Joined:
    Aug 16, 2012
    Messages:
    9
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    http://www.vaayaaedu.com/
    great reference. I was looking for URL encode in ASP
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice