More URI-Related UDFs

To follow up my parseUri() function, here are several more UDFs I've written recently to help with URI management:

  • getPageUri()
    Returns a struct containing the relative and absolute URIs of the current page. The difference between getPageUri().relative and CGI.SCRIPT_NAME is that the former will include the query string, if present.
  • matchUri(testUri, [masterUri])
    Returns a Boolean indicating whether or not two URIs are the same, disregarding the following differences:
    • Fragments (page anchors), e.g., "#top".
    • Inclusion of "index.cfm" in paths, e.g., "/dir/" vs. "/dir/index.cfm" (supports trailing query strings).
    If masterUri is not provided, the current page is used for comparison (supports both relative and absolute URIs).
  • replaceUriQueryKey(uri, key, substring)
    Replaces a URI query key and its value with a supplied key=value pair. Works with relative and absolute URIs, as well as standalone query strings (with or without a leading "?"). This is also used to support the following two UDFs:
  • addUriQueryKey(uri, key, value)
    Removes any existing instances of the supplied key, then appends it together with the provided value to the provided URI.
  • removeUriQueryKey(uri, key)
    Removes one or more query keys (comma delimited) and their values from the provided URI.

View the source code.

Now that I have these at my disposal, I frequently find myself using them in combination with each other. E.g.:

<a href="<cfoutput>#addUriQueryKey(

Let me know if you find any of these useful.

In other news, this cracked me up.

3 thoughts on “More URI-Related UDFs”

  1. Sadly, CGI.QUERY_STRING doesn’t escape its ampersands, so we must add them back in:
    <cfset pageQuery = reReplace(“?” & reReplace(CGI.QUERY_STRING, “&(?:(?=\s)|(?!(?:\w{2,7}|##\d{2,5});))”, “&amp;”, “ALL”), “\?$”, “”) />

    See line 15.

  2. Hey Matt!

    Since CGI.QUERY_STRING is used in non-HTML-rendering contexts, it would be inappropriate for CF to automatically use HTML entities in its value. If you want to use the value in valid HTML, yes, the ampersands need to be replaced with “&amp;”, but I’d recommend something along the lines of the more straightforward <cfif len(cgi.query_string)><cfset queryHtml = "?" & replace(cgi.query_string, "&", "&amp;", "all") /></cfif>. Excluding some ampersands from HTML encoding as is done in your above regex seems incorrect here, unless I’m missing something.

  3. Your solution is applicable in the vast majority of cases. I was trying to account for ampersands in the query string that were already part of an encode — for instance “&szlig;” But then again, such ampersands would ultimately be interpreted as normal query string delimiters — if they hadn’t already been URL-encoded as “%26“.

Leave a Reply

Your email address will not be published. Required fields are marked *