In AnQiCMS template development, when we handle URL parameters, we often encounter the need to encode them.This is mainly to ensure the legality of the URL, avoid special characters from destroying the URL structure, and correctly transmit data containing non-ASCII characters (such as Chinese).urlencodeandiriencodeThese two filters help us complete this task, but their application scenarios and coding differences are not the same.
Understanding the basics of URL encoding
Before delving into these two filters, let's briefly review the necessity of URL encoding.URL (Uniform Resource Locator) defines a set of allowed characters.?)、&(&)and equal sign(=)etc., has a specific meaning in URLs.If not encoded, they may be misunderstood as part of the URL structure, resulting in URL parsing errors.Moreover, non-ASCII characters (such as Chinese characters, Japanese, etc.) cannot appear directly in URLs and need to be converted to Percent-encoding form.
The template engine provided by AnQiCMS offersurlencodeandiriencodeAims to solve these problems, but they are focused on "how to encode" and "what to encode".
urlencodeFilter: Comprehensive protection of URL security
urlencodeThe filter performs the most common and most comprehensive URL encoding. Its main responsibility is to encode all theUnsafeThe characters (including spaces, special symbols, and non-ASCII characters) are all converted to percentage-encoded form.Here, the term 'insecure' usually refers to those characters that may cause ambiguity or are not allowed to appear directly in URL paths or query strings.
Application scenario:
- Encode the entire URL:When you need to pass a complete URL as a parameter value for another URL, in order to avoid the special characters of the internal URL (such as
?/&//)Conflicts with the structure of the external URL, you need to modify the entire internal URLurlencode. - Encode a component of the URL as plain data:If you are sure that a string will be used as a value for a parameter in a URL (such as a search keyword, or a file path), and that value may contain any special characters or even the entire URL, then use
urlencodeIs **auto**, to ensure it is treated as pure data processing and not misinterpreted as a URL structure by the server. - Ensure the integrity of the data in the HTTP request:In some advanced scenarios, when a string containing a URL is sent via HTTP headers or a special request body,
urlencodeit can provide the strongest character compatibility.
Encoding differences:
urlencodeEncodes almost all special characters, including:///?/&/=them into their equivalent representations, which%XX. This means it will disrupt the original structure separators of the URL.
Example:
Assuming you have a URL that contains special characters and query parameters, and you want to use it as the value of another parameter: “`twig {# Your original link is: http