What's valid and what's not in a URI query?
Asked Answered
T

7

121

Background (question further down)

I've been Googling this back and forth reading RFCs and SO questions trying to crack this, but I still don't got jack.

So I guess we just vote for the "best" answer and that's it, or?

Basically it boils down to this.

3.4. Query Component

The query component is a string of information to be interpreted by the resource.

query = *uric

Within a query component, the characters ";", "/", "?", ":", "@", "&", "=", "+", ",", and "$" are reserved.

The first thing that boggles me is that *uric is defined like this

uric = reserved | unreserved | escaped

reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","

This is however somewhat clarified by paragraphs such as

The "reserved" syntax class above refers to those characters that are allowed within a URI, but which may not be allowed within a particular component of the generic URI syntax; they are used as delimiters of the components described in Section 3.

Characters in the "reserved" set are not reserved in all contexts. The set of characters actually reserved within any given URI component is defined by that component. In general, a character is reserved if the semantics of the URI changes if the character is replaced with its escaped US-ASCII encoding.

This last excerpt feels somewhat backwards, but it clearly states that the reserved character set depends on context. Yet 3.4 states that all the reserved characters are reserved within a query component, however, the only things that would change the semantics here is escaping the question mark (?) as URIs do not define the concept of a query string.

At this point I've given up on the RFCs entirely but found RFC 1738 particularly interesting.

An HTTP URL takes the form:

http://<host>:<port>/<path>?<searchpart>

Within the <path> and <searchpart> components, "/", ";", "?" are reserved. The "/" character may be used within HTTP to designate a hierarchical structure.

I interpret this at least with regards to HTTP URLs that RFC 1738 supersedes RFC 2396. Because the URI query has no notion of a query string also the interpretation of reserved doesn't really let allow me to define query strings as I'm used to doing by now.

Question

This all started when I wanted to pass a list of numbers together with the request of another resource. I didn't think much of it, and just passed it as a comma separated values. To my surprise though the comma was escaped. The query page.html?q=1,2,3 encoded turned into page.html?q=1%2C2%2C3 it works, but it's ugly and didn't expect it. That's when I started going through RFCs.

My first question is simply, is encoding commas really necessary?

My answer, according to RFC 2396: yes, according to RFC 1738: no

Later I found related posts regarding the passing of lists between requests. Where the csv approach was poised as bad. This showed up instead, (haven't seen this before).

page.html?q=1;q=2;q=3

My second question, is this a valid URL?

My answer, according to RFC 2396: no, according to RFC 1738: no (; is reserved)

I don't have any issues with passing csv as long as it's numbers, but yes you do run into the risk of having to encode and decode values back and forth if the comma suddenly is needed for something else. Anyway I tried the semi-colon query string thing with ASP.NET and the result was not what I expected.

Default.aspx?a=1;a=2&b=1&a=3

Request.QueryString["a"] = "1;a=2,3"
Request.QueryString["b"] = "1"

I fail to see how this greatly differs from a csv approach as when I ask for "a" I get a string with commas in it. ASP.NET certainly is not a reference implementation but it hasn't let me down yet.

But most importantly -- my third question -- where is specification for this? and what would you do or for that matter not do?

Talbert answered 2/3, 2010 at 19:51 Comment(3)
How can RFC 1738 supersede RFC 2396, when RFC 2396 was published almost 4 years later?Rind
With regard to URLs and what practically makes sense, it is my interpretation that it does. (supersede is probably not the right word though, because it's been used in RFC terminology to deprecated old RFCs, RFC 1738 doesn't feel all that deprecated when it is the only spec if found that allows you to put a query string in the searchpart of the URL)Talbert
Could you provide links for the quoted matter above?Vlissingen
L
86

That a character is reserved within a generic URL component doesn't mean it must be escaped when it appears within the component or within data in the component. The character must also be defined as a delimiter within the generic or scheme-specific syntax and the appearance of the character must be within data.

The current standard for generic URIs is RFC 3986, which has this to say:

2.2. Reserved Characters

URIs include components and subcomponents that are delimited by characters in the "reserved" set. These characters are called "reserved" because they may (or may not) be defined as delimiters by the generic syntax, by each scheme-specific syntax, or by the implementation-specific syntax of a URI's dereferencing algorithm. If data for a URI component would conflict with a reserved character's purpose as a delimiter [emphasis added], then the conflicting data must be percent-encoded before the URI is formed.

   reserved    = gen-delims / sub-delims

gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"

sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="

3.3. Path Component

[...]
pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
[...]

3.4 Query Component

[...]
      query       = *( pchar / "/" / "?" )

Thus commas are explicitly allowed within query strings and only need to be escaped in data if specific schemes define it as a delimiter. The HTTP scheme doesn't use the comma or semi-colon as a delimiter in query strings, so they don't need to be escaped. Whether browsers follow this standard is another matter.

Using CSV should work fine for string data, you just have to follow standard CSV conventions and either quote data or escape the commas with backslashes.

As for RFC 2396, it also allows for unescaped commas in HTTP query strings:

2.2. Reserved Characters

Many URI include components consisting of or delimited by, certain special characters. These characters are called "reserved", since their usage within the URI component is limited to their reserved purpose. If the data for a URI component would conflict with the reserved purpose, then the conflicting data must be escaped before forming the URI.

Since commas don't have a reserved purpose under the HTTP scheme, they don't have to be escaped in data. The note from § 2.3 about reserved characters being those that change semantics when percent-encoded applies only generally; characters may be percent-encoded without changing semantics for specific schemes and yet still be reserved.

Lascar answered 3/3, 2010 at 22:46 Comment(0)
U
33

I think the real question is: "What characters should be encoded in a query string?" And that depends mainly on two things: The validity and the meaning of a character.

Validity according to the RFC standard

In RFC3986 we can find which special characters are valid and which are not inside a query string:

// Valid:
! $ & ' ( ) * + , - . / : ; = ? @ _ ~
% (should be followed by two hex chars to be completely valid (e.g. %7C))

// Invalid:
" < > [ \ ] ^ ` { | }
space
# (marks the end of the query string, so it can't be a part of it)
extended ASCII characters (e.g. °)

Deviations from the standard

Browsers and web frameworks do not always strictly follow the RFC standard. Below are some examples:

[, ] are not valid, but Chrome and Firefox do not encode these characters inside a query string. The reasoning given by Chrome devs is simply: "If other browsers and an RFC disagree, we will generally match other browsers." QueryHelpers.AddQueryString from ASP.NET Core on the other hand will encode these characters.

Other invalid characters that are not encoded by Chrome and Firefox are:

\ ^ ` { | }

' is a valid character inside a query string but will be encoded by Chrome, Firefox and QueryHelpers nevertheless. The explanation given by Firefox devs is that they knew that they don't have to encode it according to the RFC standard, but did it to reduce vulnerabilities.

Special meaning

Some characters are valid and also don't get encoded by browsers, but should still be encoded in certain cases.

+: Spaces are normally encoded as %20 but alternatively they can be encoded as +. So + inside a query string means it's an encoded space. If you want to include a character that's actually supposed to literally mean plus, then you have to use the encoded version of + which is %2B.

~: Some old Unix systems interpreted URI parts that started with ~ as a path to a home directory. So it's a good idea to encode ~ if it's not meant to denote the start of a Unix home directory path for an old system (so nowadays probably always encode).

=, &: Usually (although RFC doesn't specify that this is required) query strings contain parameters in the format "key1=value1&key2=value2". If that's the case and =s or &s should be part of the parameter key or the parameter value instead of giving them the role of separating the key and value or separating the parameters, then you have to encode those =s and &s. So if a parameter value should for some reason consist of the string "=&" then it has to be encoded as %3D%26 which then can be used for the full key and value: "weirdparam=%3D%26".

%: Usually web frameworks figure out that %s that are not followed by two hex characters simply mean the % itself, but it's still a good idea to always encode % when it's supposed to only mean % and not indicate the start of an encoded character (e.g. %7C) because RFC3986 specifies that % is only valid when followed by two hex characters. So don't use "percentageparam=%" use "percentageparam=%25" instead.

Encoding guidelines

Encode every character that is otherwise invalid* according to RFC3986 and every character that can have special meaning but should only be interpreted in a literal way without giving it a special meaning. You can also encode things that aren't required to be encoded, like '. Why? Because it doesn't hurt to encode more than necessary. Servers and web frameworks when parsing a query string will decode every encoded character, no matter if it was really necessary to previously encode that character or not.

The only characters of a query string that shouldn't be encoded are those that can have a special meaning and shouldn't lose that special meaning, e.g. don't encode the = of "key1=value1". For that to achieve don't apply an encoding method to the whole query string (and also not to the whole URI) but apply it only and separately to the query parameter keys and values. For example, with JS:

var url = "http://example.com?" + encodeURIComponent(myKey1) + "=" + encodeURIComponent(myValue1) + "&" + encodeURIComponent(myKey2)...;

Note that encodeURIComponent encodes a lot more characters than necessary meaning characters that are valid in a query string and don't have special meaning there e.g. /, ?, ... The reason is that encodeURIComponent wasn't created for query strings alone but instead encodes characters that have special meaning outside of the query string as well, e.g. / for the path URI component. QueryHelpers.AddQueryString works in a similar manner. Under the hood it uses System.Text.Encodings.Web.DefaultUrlEncoder which is not just meant for query strings but also for isegment, ipath-noscheme and ifragment.

* You could probably get away with only regarding those characters as invalid that are both not allowed by the RFC and that are also always encoded by Chrome for instance. This would be Space " < >. But it's probably better to be on the safer side and encode at least everything that RFC3986 considers invalid.

OP's questions

My first question is simply, is encoding commas really necessary -> No it's not necessary, but it doesn't hurt (except ugliness) and will happen with default encoding methods e.g. encodeURIComponent and decoding and query string parsing should work nevertheless.

My second question, is this a valid URL (page.html?q=1;q=2;q=3)? -> It's RFC valid, but your server / web framework might have a hard time parsing the query string when it might expect the typical "key1=value1&key2=value2" format for query strings.

Where is specification for this? -> There isn't a single specification that covers everything because some things are implementation specific. For instance there are different ways of specifying arrays inside of query strings.

Unplug answered 7/6, 2016 at 13:25 Comment(10)
Is https://stackoverflow.com/questions/2366260/whats-valid-and-whats-not-in-a-uri-query?param=b#1;c#2 a valid query parameter?Juvenilia
@SumitJain No, because # cannot appear inside the query portion of a URI as-is. You will need to encode it as %23, so that URI should be https://stackoverflow.com/questions/2366260/whats-valid-and-whats-not-in-a-uri-query?param=b%231;c%232.Cabbage
weird. single quote ' is allowed in rfc3986, rfc2396 and others and left alone by encodeURIComponent, as it should be. However, I also noticed that chrome was escaping it in URI queriesUndervalue
bracket is now encoded as %5B and %5D. Example encodeURI('mozilla.org/?x[2]=hello') will give 'mozilla.org/?x%5B2%5D=hello'Deodar
@Deodar With Chrome it doesn't seem to get encoded.Unplug
@Unplug tried above inside chrome console, it's encoded. So wasn't sure what you referring to when you said it's not encoded.Deodar
@Deodar I entered the URL in the address bar and then checked the actually requested URL using the dev tools. Stuff like > gets encoded this way, [] doesn't.Unplug
@Unplug wasn't sure if we should use unencoded [] directly on the chrome url bar or not, as by right user should give a properly formatted URL? encodeURI told us that bracket should be encoded in that sense.Deodar
@Deodar encodeURI isn't meant for query strings. For instance it keeps # although # cannot be part of a query string (it marks the end of the query string instead). Anyway, you have a point though about []. I will update my answer over the next days. BTW here is the reason why Chrome doesn't encode [] (it seems to be because of IE): bugs.chromium.org/p/chromium/issues/detail?id=74424Unplug
@Unplug yap, for query string, use encodeURIComponent("abc=#567"),Deodar
E
11

Just use ?q=1+2+3

I am answering here a fourth question :) that did not ask but all started with: how do i pass list of numbers a-la comma-separated values? Seems to me the best approach is just to pass them space-separated, where spaces will get url-form-encoded to +. Works great, as longs as you know the values in the list contain no spaces (something numbers tend not to).

Edwardedwardian answered 16/2, 2014 at 21:31 Comment(1)
While this should be a comment (as it does not answer the question), thank you. + makes even more sense in the specific case that I was looking to use a comma.Sprightly
P
7

page.html?q=1;q=2;q=3

is this a valid URL?

Yes. The ; is reserved, but not by an RFC. The context that defines this component is the definition of the application/x-www-form-urlencoded media type, which is part of the HTML standard (section 17.13.4.1). In particular the sneaky note hidden away in section B.2.2:

We recommend that HTTP server implementors, and in particular, CGI implementors support the use of ";" in place of "&" to save authors the trouble of escaping "&" characters in this manner.

Unfortunately many popular server-side scripting frameworks including ASP.NET do not support this usage.

Pullen answered 2/9, 2011 at 18:15 Comment(4)
So while the ?q=1;q=2;q=3 query is valid, it is ambiguous: some server-side frameworks will read it to mean { q: '1;q=2;q=3' }, other may do it akin to { q: {'1', '2', '3'}}.Edwardedwardian
Yes. And what's worse, HTML5 now doesn't include the language about ;, meaning that HTML4 and HTML5 are inconsistent. Ugh, the perils of non-normative language in a spec document...Pullen
@NasBanov And yet others (e.g. PHP) will interpret it as { q: 3 }Fibriform
@NicholasShanks - where PHP is involved, all bets are off! :)Edwardedwardian
A
1

I would like to note that page.html?q=1&q=2&q=3 is a valid url as well. This is a completely legitimate way of expressing an array in a query string. Your server technology will determine how exactly that is presented.

In Classic ASP, you check Response.QueryString("q").Count and then use Response.QueryString("q")(0) (and (1) and (2)).

Note that you saw this in your ASP.NET, too (I think it was not intended, but look):

Default.aspx?a=1;a=2&b=1&a=3

Request.QueryString["a"] = "1;a=2,3"
Request.QueryString["b"] = "1"

Notice that the semicolon is ignored, so you have a defined twice, and you got its value twice, separated by a comma. Using all ampersands Default.aspx?a=1&a=2&b=1&a=3 will yield a as "1,2,3". But I am sure there is a method to get each individual element, in case the elements themselves contain commas. It is simply the default property of the non-indexed QueryString that concatenates the sub-values together with comma separators.

Analysis answered 20/10, 2012 at 4:48 Comment(0)
D
1

I had the same issue. The URL that was hyperlinked was a third party URL and was expecting a list of parameters in format page.html?q=1,2,3 ONLY and the URL page.html?q=1%2C2%2C3 did not work. I was able to get it working using javascript. May not be the best approach but can check out the solution here if it helps anyone.

Dodecanese answered 9/12, 2014 at 20:44 Comment(1)
Some web frameworks allow multiple values to be associated with a single field, but that's only a recommendation. There is no requirement for how a query string must be parsed by a particular website. Your third-party site probably treats an unencoded comma as a delimiter between multiple values but treats encoded commas as part of a single value. That's a sensible option.Ketubim
P
-5

If you are sending the ENCODED characters to FLASH/SWF file, then you should ENCODE the character twice!! (because of Flash parser)

Passer answered 9/7, 2015 at 14:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.