Search code examples
phpselfreferer

PHP detect if page is reloaded with PHP_SELF


I have a form that reloads the page with the updated data:

<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    ...
    <input type="submit" name="Submit" value="Update data">
</form>

When the page is updated I want to display a message "Data updated". There was something like this with Referer I beleve, but can't remember.

btw I am also using:

if (isset($_POST['Submit'])) {
    // prevent resending data
    header("Location: " . $_SERVER['PHP_SELF']);
}

to avoid the annoying resending data message when the user clicks the back button. Is this correct?


Solution

  • If you want to be absolutely sure that a form was submitted, you can store a variable in a session:

    session_start();      // at top of page
    ...
    if (isset($_POST['Submit'])) {
        $_SESSION['form_submitted'] = true;
        ...
        // prevent resending data
        header("Location: " . $_SERVER['PHP_SELF']);
    }
    elseif ($_SESSION['form_submitted'])
    {
        ...
    }
    

    Less reliable but also possible is the use of $_SERVER['HTTP_REFERER'] to detect what page the visitor came from.