user114671
user114671

Reputation: 532

Using $_POST information only once

I have some information which gets passed from a form and needs to be used once and only once. I can collect it nicely from $_POST but I'm not sure which is the "best" way to ensure that I can only use it once, i.e. I want to avoid the user pressing F5 repeatedly and accessing the function more than once.

My initial thought was to set a session variable and time the function out for a set period of time. The problem with that is thay could have access to the function again after the set period has elapsed.

Better ideas welcomed!

Upvotes: 2

Views: 3536

Answers (5)

Dinoart
Dinoart

Reputation: 11

To avoid the user refreshing the page and accessing to the information, You can use the token method in the form like this:

<?php 
if ( isset($_POST['submit'], $_POST['token']) && ($_POST['token'] === $_SESSION['token']) )
{
    // do something here
}

$_SESSION['token'] = uniqid();

?>

And for the form

<form method="POST">
    <input type="hidden" name="token" value="<?= $_SESSION['token'] ?>">
    <button name="submit" class="btn btn-success">Submit</button>
</form>

Upvotes: 0

Blue42
Blue42

Reputation: 355

How about:

1) create a page with the form, eg myformpage.php

2) Make the action of the form myformpage_submit.php

3) in myformpage_submit.php do whatever it is you need to do with the posted info, like inserting into a database.

4) When finished, direct the browser to another page, eg nicework.php

This should dispose of them as you wish.

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100195

You can redirect to some other page, like doing

header("Location: index.php");

Upvotes: 1

pho
pho

Reputation: 25489

This one's VERY easy to implement.

All you need to do is this:

have your form submit to a different page, which will only handle the post information, and not display ANYTHING

Then, send a LOCATION header to redirect the browser to a new page (which will be retreived by GET) This will break the browser's repost-on-refresh behaviour

Upvotes: 5

Gian
Gian

Reputation: 13955

A redirect to another page would be sufficient to break most browser repost-on-refresh behaviour. Setting a cookie on form submit (or a session variable, as you suggest) would also work quite nicely. You could have the form submission page unset the session variable again, such that only a fresh access to the form would permit re-submitting the form.

Upvotes: 10

Related Questions