Sanitize get_query_var() url parameters

I am currently working on a site and testing its security. One of the pages has a sort feature where I pass a url parameter on how I would like the content sorted.

For example:

www.example.com/page/?sort=alpha

This works fine, but I tried to send malicious code as well:

www.example.com/page/?sort=alpha%3Cimg+src=xyz+onerror=alert(99)%3E%3Cxss/%3E

In internet explorer when I enter this url my page shows up and a javascript alert pops up, thus I was able to execute some code on the page. Inside of Chrome I get the message that the XSS auditor has blocked this execution, but I rather it never even be attempted to run. From what I can see, this parameter is accepted in my header.php file under Sort : <?= get_query_var('sort') ?>.

I want to sanitize this input so that it will never execute such a script, how can I do this?

1 Answer
1

There’s a slight disconnect between your question title and the actual question.

It sounds like you’re using a plugin (or developing a plugin?) that allows for some front-end sorting. If it’s a plugin you’re using and the query string parameter is not sanitized, you need to notify that plugin’s developer, because that’s a security issue.

Fixing it yourself might solve the problem – for a while, but you really shouldn’t be editing plugins directly (even poorly coded ones) since that leaves you in the bad position of needing to re-apply any changes when there’s an update to the plugin.

The name of the get_query_var() function can be confusing. A lot of people look at this as a handy WP substitute for $_GET[], but that’s not what it does. get_query_var() is ONLY for variables that are set as part of the global WP query. This includes a number of WP defaults, along with any custom variables (added with set_query_var()).

A plugin that applies a custom URL rewrite for its endpoints might be an example of this. But if you think you can use it to just grab any query variable from the URL, that won’t work because that’s not what get_query_var() does.

You need to just search out where this query argument is collected. Most likely it’s done using $_GET['sort'].

Whatever that is, it should be:

$some_var = sanitize_text_field( $_GET['sort'] );

Or even better:

$some_var = ( isset( $_GET['sort'] ) ) ? sanitize_text_field( $_GET['sort'] ) : 'some default value';

Obviously, I’m answering based on some assumptions, the details of which were not included in your question. If I’m off base, update your question to include more info and I’ll edit accordingly.

Leave a Comment