1

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>
Machavity
  • 30,841
  • 27
  • 92
  • 100
zm455
  • 489
  • 11
  • 26
  • 3
    Sidenote: You shouldn't rely on `$_SERVER['HTTP_REFERER']` http://stackoverflow.com/a/6023980/1415724 – Funk Forty Niner Sep 21 '16 at 14:53
  • 1
    The reason being, is that you're using the same file, so it redirects to the same one, uses the GET method and appends the `$page?val=1`. It's pretty much self-explanatory. Redirect it to another page instead. – Funk Forty Niner Sep 21 '16 at 14:55

1 Answers1

2

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.
}
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Machavity
  • 30,841
  • 27
  • 92
  • 100