URL query parameters really come in handy. For example, in eForm we use data from query parameters to pre-populate/prefil form elements.
But what is the most effective, foolproof way to get the data? Is a simple $_REQUEST[ $key ] enough? Of course not. The reasons being:
- WordPress adds slashes to the $_REQUEST array before-hand. So even if magic quote is turned off, you will get slashes.
- The raw data can expose to cross site vulnerability like XSS.
So I put together a really simple function to properly get values from the URL parameters. You can use it whereever you like.
<?php
/**
* Gets the request parameter.
*
* @param string $key The query parameter
* @param string $default The default value to return if not found
*
* @return string The request parameter.
*/
function get_request_parameter( $key, $default = '' ) {
// If not request set
if ( ! isset( $_REQUEST[ $key ] ) || empty( $_REQUEST[ $key ] ) ) {
return $default;
}
// Set so process it
return strip_tags( (string) wp_unslash( $_REQUEST[ $key ] ) );
}
Here three things are happening.
- First we check if the request key is present or not. If not, then just return a default value.
- If it is set, then we first remove slashes by doing
wp_unslash. Read here why it is better thanstripslashes_deep. - Then we sanitize the value by doing a simple
strip_tags. If you expect rich text from parameter, then run it throughwp_ksesor similar functions.