zm455
zm455

Reputation: 499

Query string is appending when using $_SERVER['HTTP_REFERER']

Can someone explain me why when I execute this code multiple times it append the substring ?val=1 to my url?

Example: My script is located in index.php and if I execute it 3 times I will have this url in my browser: http://localhost/index.php?val=1?val=1?val=1

I would like to have 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>

Upvotes: 1

Views: 69

Answers (1)

Machavity
Machavity

Reputation: 31654

Just add a test before appending ?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.
}

Upvotes: 2

Related Questions