How to Write Valid URL Query String Parameters

Posted on November 30, 2008 in Structure by

When building web pages, it is often necessary to add links that require parameterized query strings. For example, when adding links to the various validation services, you may find yourself linking to an accessibility checker, such as the freely available Cynthia service:

<a href="http://www.contentquality.com/mynewtester/cynthia.exe?Url1=http://domain.tld/&rptmode=2">WCAG Accessibility Check</a>

Another example is seen when linking your feed to a feed validation service:

<a href="http://validator.w3.org/feed/check.cgi?url=http://feeds.feedburner.com/domainfeed">RSS Feed Validation</a>

And one final example showing a more complex query string:

<a href="http://delicious.com/post?url=http://domain.tld/&title=The title of a post">Bookmark at Delicious</a>

As is, however, these links won’t validate due to a number of issues. Let’s fix ‘em up with a few quick-and-easy changes.

Replace ampersands with &amp;

One of the reasons these links aren’t validating is because they contain non-encoded ampersand ( & ) characters. Ampersands are often used in URL query strings to demarcate granular chunks of information, for example:

http://domain.tld/function.cgi?url=http://fonzi.com/&name=Fonzi&mood=happy&coat=leather

..which provides several different chunks of information about everybody’s favorite hellion. To get this code to validate, we need to encode the ampersands with &amp;, for example:

http://domain.tld/function.cgi?url=http://fonzi.com/&amp;name=Fonzi&amp;mood=happy&amp;coat=leather

Replacing the ampersand characters with encoded equivalents does not change the functionality of the query string, but it does produce completely valid code.

Encode other special characters

Let’s return to our Delicious example for a moment:

<a href="http://delicious.com/post?url=http://domain.tld/&amp;title=The title of a post">Bookmark at Delicious</a>

The ampersand has been fixed, but this code still won’t validate due to the blank spaces in the title parameter. To fix this, we need to encode those blank spaces with their escaped hexadecimal equivalents, like so:

<a href="http://delicious.com/post?url=http://domain.tld/&amp;title=The%20title%20of%20a%20post">Bookmark at Delicious</a>

..such that

&amp;title=The title of a post

becomes

&amp;title=The%20title%20of%20a%20post

..which is to say that a blank space is equivalent to “%20”.

Likewise, you should also encode any other special characters. For example, here is that previous feed validation link:

<a href="http://validator.w3.org/feed/check.cgi?url=http://feeds.feedburner.com/domainfeed">RSS Feed Validation</a>

If needed, we could encode the special characters in the url parameter like so:

<a href="http://validator.w3.org/feed/check.cgi?url=http%3A%2F%2Ffeeds.feedburner.com%2Fperishablepress">RSS Feed Validation</a>

As you can see, we have made the following replacements:

: with %3A
/ with %2F

As before, the encoded values function just as well as the non-encoded characters, with the added bonus that your code will validate!

Here is a good list of URL character codes

Tips and Tricks

The previous examples demonstrate the logic and technique behind writing valid URL query string parameters, but there are easier, more efficient ways to produce valid, dynamic links. First of all, rather than manually replacing each and every special character with its encoded equivalent, we can use the magical powers of PHP’s urlencode() function.

Let’s take an example from my recent article, Fully Valid, SEO-Friendly Social Media Links for WordPress:

<a href="http://twitter.com/home?status=Currently reading: <?php the_permalink(); ?>">Tweet this!</a>

This example provides a link to enable users to quickly post the URL of your posts to their Twitter feed. As is, the blank spaces in the status parameter render the code invalid. To change this, we use the urlencode() function like so:

<a href="http://twitter.com/home?status=<?php echo urlencode("Currently reading: "); ?><?php the_permalink(); ?>">Tweet this!</a>

..which is now completely valid. Using this technique, we can encode any character string dynamically and easily. For WordPress users, we can even use urlencode() to dynamically encode various template tags such as get_the_title(), for example:

<a href="http://delicious.com/post?url=<?php the_permalink(); ?>&amp;title=<?php echo urlencode(get_the_title($id)); ?>">Bookmark at Delicious</a>

This technique makes it possible to include sitewide, post-specific, parameterized links using a single line of code. And best of all? The code is completely valid! Nice :)

Related articles

27 Responses

  1. [ Gravatar Icon ] John says:

    And in the end, the URL just becomes god-awful ugly. It’s necessary, nonetheless.

  2. [ Gravatar Icon ] Bill says:

    Another option if couldn’t do it until the client side for some reason would be the JavaScript encodeURIComponent() Function.

    http://www.w3schools.com/jsref/jsref_encodeURIComponent.asp

  3. [ Gravatar Icon ] Louis says:

    Speaking of good-looking URL, I’ve always admired the way Wikipedia handles the latters.

  4. [ Gravatar Icon ] Jeff Starr says:

    @John: True, but ugly, valid URLs are always better than less-ugly invalid URLs!

    @Bill: Thanks for the tip! Will definitely come in handy! :)

    @Louis: Are you referring to Wikipedia’s URL formatting, or something else?

  5. [ Gravatar Icon ] Loïc Hoguin says:

    You might want to take a look at http_build_query too.

  6. [ Gravatar Icon ] Louis says:

    @Jeff: I’m referring to their UTF-8-ish URL style. Here’s an example of Cool URL.

  7. [ Gravatar Icon ] Jamp Mark says:

    always use urlencode() when dealing with query parameter values.

  8. [ Gravatar Icon ] Jeff Starr says:

    @Loïc Hoguin: that is a great function for building URL query parameters, but I am not sure that it automatically encodes anything..

    @Louis: ah, I see.. yes those are very sweet looking, but they certainly don’t validate. I would love to peak at their URL scripts!

    @Jamp Mark: yes, that pretty much sums it up! ;)

  9. Brilliant post. This really clears up all the queries I had about url encoding etc.

    Thanks again Jeff

  10. [ Gravatar Icon ] Jeff Starr says:

    My pleasure, Jonathan — glad to be of service! :)

  11. [ Gravatar Icon ] Eli Geske says:

    I have a peculiar situation that I am seeking some input on.

    I am building a custom content management tool using a separate database outside of wordpress, but the client still wants the skin to be wordpress. I created my own controller that gets included() in a custom template page. I use /%category%/%postname%/ for pretty permalinks. This all works fine. But I need to pass custom parameters via the URL to trigger some of my data on my custom template page that has nothing to do with wordpress. for example:

    http://mysite.com/my-wp-pagename?myparam=myvalue&amp;moreparam=moremyvalues.

    Well Wordpress thinks I am trying to select something from the database out of wp-categories, which doesnt even exist. This only shows up in the Apache error log. But if using header redirects crashes the site and timesout.

    QUESTION: Any ideas on how to pass custom parameters in the URL without having wordpress thinking their for wordpress????

    Any help on this one would be great.

    Thanks. If i find resolve I ll reply back.

  12. [ Gravatar Icon ] Jeff Starr says:

    Hi Eli, that’s a new one for me - haven’t done that before. I would be surprised if there wasn’t something posted somewhere about that on the Web (but certainly you’ve already searched)..

    Definitely let us know if you find a solution - I’m sure it would help others in the same situation.

  13. [ Gravatar Icon ] Ashfame says:

    Thanks a bunch! I fixed my code. Earlier was trying php functions on some hardcoded links but this did it easily :)

  14. [ Gravatar Icon ] sambhu says:

    Hi

    Thanks for the nice article.

    I’ve got a quesion though. I use zend framework and trying use similar thing for preety URL. eg: http://mysite.com/name/blah/url/http://www.blah.com

    It doesn’t work even I url-encode the url part (replaced : and slashes). It gives me apache error.

    Do you have any solution for this?

    Ta

  15. [ Gravatar Icon ] Jeff Starr says:

    Hi sambhu, I do not know why that is happening. Sounds like a syntax error or something weird happening on the server. Contact your host if you know the code should work.

  16. [ Gravatar Icon ] karl willo says:

    Hi this has been a great read, but i still need some help if anyone can. Im trying to pass on the ‘id’ value from my results page to the details page. I have had it working using the querystring below. It worked when i was only getting info from one table, but now i have INNER JOINED 2 tables its not working.

    <a href="DetailsPet.phpid=">details</a>

    Im new too Php and its got me stumped. Im thinking its to do with the ‘id’ - do i need say which ‘id’ too pass the value of. As both tables are joined using ‘id’ any help with this would be great

  17. [ Gravatar Icon ] link says:

    olwebty - Thank you, nzkwrdc.

  18. [ Gravatar Icon ] MM says:

    After I upgraded to Wordpress 3.2, I have noticed that WP-Filebase is inserting “%20″ in place of spaces in shortcode when I create a link to a file.

    This was how it was done before the upgrade, which worked OK:

    [wpfilebase tag=fileurl id=72]

    But now it is doing this:

    [wpfilebase%20tag=fileurl%20id=72]

    which is not OK, because this creates a long list of ALL files in WP-Filebase directory!:

    Overall encoding for the WP site is set at UTF-8 in the Settings.

    I have deactivated and reactivated WP-Filebase.

    Anyone have any idea of what I need to do to correct this issue?

    Thanks for your advice!

  19. [ Gravatar Icon ] Jeff Starr says:

    Hey MM, I wish I knew, I would love to help, but I’m unfamiliar with WP-Filebase. I would contact the author of the Filebase plugin and see if there is a solution or workaround for the issue. Good luck!

  20. [ Gravatar Icon ] Steve says:

    Hi there,

    Thanks for the article! Shouldn’t the equal sign also be encoded?

    i.e.

    &title=The%20title%20of%20a%20post

    should be

    &title%3DThe%20title%20of%20a%20post

    I’ve seen API suggestions that don’t encode, so maybe I’m wrong, but haven’t read anything contrary to my understanding of this in the spec.

    From [RFC2396]:

    3.4. Query Component

    The query component is a string of information to be interpreted by
    the resource.

    query = *uric

    Within a query component, the characters “;”, “/”, “?”, “:”, “@”,
    “&”, “=”, “+”, “,”, and “$” are reserved.

  21. [ Gravatar Icon ] Jeff Starr says:

    Hey Steve, as far as I know there is no need to encode the equal sign, as it’s reserved for literal inclusion within URIs.

  22. [ Gravatar Icon ] Mo says:

    Hello.

    How would you do this.

    Http://www.site.com/?n=1&amp;URL=http://my.com?a=3

    There are multiple querystrings. My site is ignoring the second

  23. [ Gravatar Icon ] Ladida Cafe says:

    hey there, thanks for the tips, buat I have a problem here

    <a expr:href='&quot;http://digg.com/submit?phase=2&amp;amp;url=&quot; + data:post.url + &quot;&amp;amp;title=&quot; + data:post.title'/>

    how to fix that? how to use %20 in place of spaces?

  24. [ Gravatar Icon ] Chaz says:

    Hello,
    I am working on an unfinished site for a friend of mine and I have no idea where these id’s ? are pointing to. Are they pointing to folders and files on his server?
    It’s a flash engine which pulls different editable images into it, and he had a falling out with the gentleman that was building the site for him.
    I know that the “bt_design is an swf file, but i’m lost on the rest of the string.

  25. [ Gravatar Icon ] Chaz says:

    Sorry, here it is.

    param name="FlashVars" value="ver=mk_design&amp;t=orderFromTpl&amp;
    tid=1513&amp;category_id=484&amp;uid=4af4dc0449&amp;sku=484"

  26. [ Gravatar Icon ] Jeff Starr says:

    Hey Chaz, generally speaking URL parameters are used by scripting languages such as PHP to keep track of things and enable specific, context-specific functionality.

    So if it were me, I would look at the site files and maybe scan/search for some of the parameter names to get an idea of their purpose.

    Hopefully that helps!

  27. [ Gravatar Icon ] Chaz says:

    Hey Jeff,
    Thanks for getting back to me so quickly. I saw the sample, that the above code came from work on the coders test site, but he never created folders for the parameters, or uploaded content. I think it was more of a take the money and run kind of thing. I can create folders and upload my friends content, i just have no clue what a tid, uid or sku are, etc. I can build wordpress sites all day long, but i’m lost on this kind of thing.
    Thank you very much. I have learned a lot from you site.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

Please use basic markup. Wrap code with <code> tags!