Which one's correct?

<img src="#encodeForHTMLAttribute(FORM.path)#">

or

<img src="#encodeForURL(FORM.path)#">

or

<img src="#encodeForHTMLAttribute(encodeForURL(FORM.path))#">

?

有帮助吗?

解决方案

Use the method(s) which match the context of where you are inserting the text that needs encoding.


encodeForUrl is for placing dynamic text into a URL - so it will replace / with %2F (and so on), and if you apply it to an entire URL, you will have an encoded URL (which is therefore broken for use in a src attribute).

If you are allowing users to supply a partial URL, you would need to split on / (and any other relevant delimiters), apply encodeForUrl on each part, then join back together again.

Note: encodeForUrl appears to pass its string straight to Java, which means backslashes are treated as escape characters - \b\n encodes to %08%0A instead of %5Cb%5Cn - this behaviour is not part of standard URL encoding (nor CF strings in general). To avoid this use the function UrlEncodedFormat instead.

encodeForHTMLAttribute is for placing dynamic text into a HTML attribute - it's purpose is to ensure the contents are treated as text (not parsed as HTML) - it doesn't know/care whether its contents is a URL or something else.


In summary, you probably want encodeForHtmlAttribute( UrlEncodedFormat( Form.Path ) ) for this situation.

其他提示

In your example the answer is to use both.

However, depending on the content of FORM.path you may break things.

The function encodeForURL should be called encodeUriComponent (as is done in Javascript) because it is intended to be used on uri components, not on the entire url string. A uri component, such as name value pairs, need to be encoded separately otherwise the seperator ("=" for name value pairs) will be encoded as well.

The following will result in a 404, even if you have an index.cfm file. Note that the path separator "/", query string separator "?" and name/value separator "=" are all encoded, making the entire string a single unit.

<a href="#encodeForURL("/index.cfm?x=y")#">here</a>

What should be done instead is:

<cfset pathURIEncoded = "/index.cfm?#encodeForURL("x")#=#encodeForURL("y")#">
<a href="#encodeForHTMLAttribute(Variables.pathURIEncoded)#">here</a>

Replacing x and y with variables and not static strings, of course.

For this example, I would use the encodeForHTMLAttribute method as it is a static path. The only exception would be if the value of the src attribute itself was generated from a publicly-accessible scope (sent via the URL, FORM etc) and contains dynamic data. If this was the case, I would use the encodeForURL() method.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top