In AnQiCMS template development, when dealing with URL parameters, we often encounter scenarios where we need to encode them.This is mainly to ensure the legality of the URL, avoid special characters from damaging the URL structure, and correctly transmit data containing non-ASCII characters (such as Chinese).AnQiCMS providedurlencodeandiriencodeThese two filters help us complete the task, but their application scenarios and coding differences are not the same.

Understanding the basics of URL encoding

Before we delve deeper into these two filters, let's briefly review the necessity of URL encoding.The URL (Uniform Resource Locator) defines a set of allowable characters.Special characters, such as spaces, question marks (?)、with symbol(&)、equals(=)Etc., has a specific meaning in URLs. If not encoded, they may be misunderstood as part of the URL structure, leading to URL parsing errors.Moreover, non-ASCII characters (such as Chinese, Japanese, etc.) cannot appear directly in URLs and must be converted to percent-encoding form.

The AnQiCMS template engine providesurlencodeandiriencodeAiming to solve these problems, but they have a focus on "how to encode" and "what to encode".

urlencodeFilter: Comprehensive security for URL

urlencodeThe filter performs the most common and comprehensive URL encoding. Its main responsibility is to encode allUnsafeThe characters (including spaces, special symbols, and non-ASCII characters) are all converted to percent-encoded format.Here "unsafe" usually refers to those characters that may cause ambiguity or are not allowed to appear directly in URL paths, query strings.

Application scenario:

  • Encode the complete URL:When you need to pass a complete URL as a parameter to 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 encode the entire internal URL.urlencode.
  • Encode a component of the URL as plain data: If you are sure that a string will be used as a parameter value in a URL (such as a search keyword or a file path), and this value may contain any special characters or even the entire URL, then useurlencodeIs**selected to ensure that it is treated as pure data processing and not misinterpreted by the server as a URL structure.
  • Ensure the integrity of the data in the HTTP request:In certain advanced scenarios, when a string containing a URL is sent through HTTP headers or a special request body,urlencodeit can provide the strongest character compatibility.

Encoding differences:

urlencodeIt encodes almost all special characters, including:///?/&/=and converts them to%XXformat. This means it will break the original structure separators of the URL.

Example:

Assume you have a URL containing special characters and query parameters that you want to use as the value of another parameter: “`twig {# The original link is: http