无法在 urlencode() 上使用 htmlspecialchars() 进行重定向

Unable to redirect with htmlspecialchars() on urlencode()

我试图在登录后将用户重定向到 requested_page,谷歌搜索后我尝试了这段代码

link登录页面

echo "<a href='/login.php?ref=". urlencode($_SERVER['REQUEST_URI']) ."'>login</a>";

并在 login.php

    if ($_GET['ref'] != '') {
        $url = $_GET['ref'];
    } else {
        $url = "/";
    }

if ($user->login($username, $password)) {
            $_SESSION['username'] = $username;
            header("location:http://" . $_SERVER['HTTP_HOST'].$url);
            exit();
        }

Above method works fine, But it is vulnerable to XSS

login.php?ref=<script>alert(%27Malicious%20content%27)</script>

所以我这样添加了htmlspecialchars()

    if ($_GET['ref'] != '') {
        $url = htmlspecialchars($_GET['ref']);
    } else {
        $url = "/";
    }

但它没有重定向,而是显示 404 error

任何帮助我如何防止 XSS 攻击

终于解决了

调试代码产生错误

if ($_GET['ref'] != '') {
    $url = htmlspecialchars($_GET['ref']);
} else {
    $url = "/";
}

<h6 class="small text-black-50">Log in with social media account or email</h6>
 <?= $_SERVER['HTTP_HOST'].$url ?>

这造成了一个问题

<?= $_SERVER['HTTP_HOST'].$url ?>

并删除此行并解决。