Which EncodeFor should be used for location?

和自甴很熟 提交于 2019-12-13 14:19:12

问题


Which EncodeFor should be used location()?

If I want to push some data via location, what should it look like?

location("obtainBDK.cfm?message=#ErrorMessage#", false); // nothing

OR

location("obtainBDK.cfm?message=#EncodeForHTMLAttribute(ErrorMessage)#", false);

OR

location("obtainBDK.cfm?message=#EncodeForURL(ErrorMessage)#", false);

OR

Something else?


回答1:


cflocation/location sets the Location HTTP header. The browser reads this value and requests the mentioned resource via HTTP GET. Said URI should be encoded.

Now the only URI part that requires encoding is the query string, which starts with a question mark ?. Each key-value-pair consist of the encoded key, an equal-sign = and the encoded value. Multiple pairs are delimited by an ampersand &.

According to RFC 1738:

Thus, only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL.

Reserved Characters Example

Unencoded URI:
http://example.org/path?&=&&===&?

Expected key-value-pairs:

- "&": "&"
- "=": "="
- "?": ""

However, a proper parser would only see empty keys and values. We need to encode keys and values so they are not treated for their technical purpose.

Encoded URI: http://example.org/path?%26=%26&%3D=%3D&%3F&%20=%20!

Now all characters in key and value are percent-encoded according to RFC 3986 and cannot be mistaken by the parser.

ColdFusion:

kvps = [];

key = "message";
val = ErrorMessage;
kvps.append(
    urlEncodedFormat(key) & "=" & urlEncodedFormat(val)
);

targetUrl = "btainBDK.cfm?" & arrayToList(kvps, "&");
location(targetUrl, false);

urlEncodedFormat vs. encodeForUrl

  • urlEncodedFormat encodes a space as %20 (percent-encoded)
  • encodeForUrl encodes a space as + (application/x-www-form-urlencoded)

Although...

Adobe recommends that you use the EncodeForURL function, not the URLEncodedFormat function, to escape special characters in a string for use in a URL in all new applications.

I encountered issues where + could not be properly distinguished between being a space or an actual plus sign, especially when the context changes (CF <-> JS). So I would recommend urlEncodedFormat regardless of Adobe's opinion about it.



来源:https://stackoverflow.com/questions/52729271/which-encodefor-should-be-used-for-location

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!