John
John

Reputation: 4706

Usage of url_encode

I tried using Ruby's url_encode (doc here.)

It encodes http://www.google.com as http%3A%2F%2Fwww.google.com. But it turns out that I cannot open the latter via a browser. If so, what's the use of this function? What is it useful for, when the URL that it encodes can't even be opened?

Upvotes: 3

Views: 748

Answers (2)

code4j
code4j

Reputation: 4626

A typical use is the HTTP GET method, in where you need a query String.

Query String 1:

valudA=john&valueB=john2

Actual value server get:

  • valueA : "john"

  • valueB : "john2"

url_encode is used to make the key-value pair enable to store the string which includes some non-ASCII encoded character such as space and special character.

Suppose the valueB will store my name, code 4 j, you need to encode it because there are some spaces.

url_encode("code 4 j")
code%204%20j

Query string 2:

valueA=john&valueB=code%204%20j

Actual value server get:

  • valueA: "john"
  • valueB: "code 4 j"

Upvotes: 2

Răzvan Flavius Panda
Răzvan Flavius Panda

Reputation: 22106

You can use url_encode to encode for example the keys/values of a GET request.

Here is an example of what a SO search query URL looks after encoding:

https://stackoverflow.com/questions/tagged/c%23+or+.net+or+asp.net

As you can see, url encoding appears to be applied only on the last part of the URL, after the last slash.

In general you cannot use url_encode on your entire URL or you will also encode the special characters in a normal URL like the :// in your example.

You can check a tutorial that explains how it works here: http://www.permadi.com/tutorial/urlEncoding/

Upvotes: 2

Related Questions