使用$ _SERVER ['HTTP_REFERER']时附加查询字符串

时间:2016-09-21 14:51:10

标签: php

有人可以解释一下为什么当我多次执行此代码时,它会将子字符串?val=1附加到我的网址?

示例:我的脚本位于index.php中,如果我执行3次,我会在浏览器中显示此网址:http://localhost/index.php?val=1?val=1?val=1

我想http://localhost/index.php?val=1。 。

<?php
        if(isset($_POST['hidden']) && $_POST['hidden'] == 2){
            $page = $_SERVER['HTTP_REFERER'];
            header("location: $page?val=1");
        }
?>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
        <input name ="hidden" value="2">
        <input type="submit">
    </form>

1 个答案:

答案 0 :(得分:2)

只需在追加?val=1

之前添加测试
if(isset($_POST['hidden']) && $_POST['hidden'] == 2){
    $page = $_SERVER['HTTP_REFERER'];
    if(strpos($page, '?val=1') === false) $page .= '?val=1';
    header("location: $page");
    exit; // Avoid further execution if more code is below this.
}