我如何处理$_SERVER['QUERY_STRING'],然后重新使用查询字符串- PHP


How can I sanitise $_SERVER['QUERY_STRING'] and then re-use the query string - PHP

在我的站点上,我使用一些PHP将移动用户重定向到单独的移动站点:

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;
    }
}

重要的是,如果请求的URL包含查询字符串,当移动流量被重定向时,它不会被删除。出于这个原因,我将查询字符串设置为一个变量,并使用"htmlspecialchars"对其进行过滤,以避免XSS攻击。然而,这有不利的影响,将查询字符串中的'&'转换为&这会破坏查询字符串,例如:

?utm_source=Google&utm_medium=ABC

就变成:

?utm_source=Google&utm_medium=ABC

我如何保护我的网站免受XSS攻击而不破坏连接到重定向URL的查询字符串?

应该可以了。http_build_query will urlencode for you:

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

嗯…但这似乎没有必要。

感谢您的回复。

最后,我刚刚删除了清理,因为这是不必要的,因为我没有在网站的任何地方执行查询字符串值。

最终代码如下:

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;
    }
}