Вопрос

On my site I use some PHP to redirect mobile users to separate mobile site:

if ($detect->isMobile()) {

    // set query string:
    $query_string = $_SERVER['QUERY_STRING'];

    // sanitise:
    $sani_query_string = htmlspecialchars($query_string);

    // if query string empty send to mobile site, else send to mobile site and concatenate query string:
    if (empty($query_string)) {
        header('Location: http://m.mywebsite.com/');
        exit;
    } else {
        header('Location: http://m.mywebsite.com/?'. $sani_query_string);
        exit;
    }

}

It's important that if the requested URL contains a query string, it is not removed when mobile traffic is redirected. For this reason I set the query string as a variable, and sanitise it using 'htmlspecialchars' to avoid XSS attacks. However, this has the adverse affect of converting '&' in the query string to &amp which break the query string eg:

?utm_source=Google&utm_medium=ABC

becomes:

?utm_source=Google&utm_medium=ABC

How can I secure my site against XSS attacks without breaking the query string that is concatenated to the redirected URL?

Это было полезно?

Решение 2

Thanks for the responses.

In the end i've just removed the sanitisation as this was unnecessary since I'm not executing the query string values anywhere on the site.

Final code as follows:

if ($detect->isMobile()) {

    // set query string:
    $query_string = $_SERVER['QUERY_STRING'];

    // if query string empty send to mobile site, else send to mobile site and concatenate query string:
    if (empty($query_string)) {
    header('Location: http://m.mywebsite.com/');
    exit;
    } else {
    header('Location: http://m.mywebsite.com/?'. $query_string);
    exit;
    }
} 

Другие советы

This should do it. http_build_query will urlencode for you:

parse_str($_SERVER['QUERY_STRING'], $vars);
$query = http_build_query($vars);

Hmmm... But this seems unnecessary.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top