Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding form resubmit in php when pressing f5

I have the following code on my site (using php and smarty) to try and avoid a form resubmitting when I hit f5:

if ($this->bln_added == false) {
    if (isset($_POST['submit'])) {
        $this->obj_site->obj_smarty->assign('title', $_POST['tas_heading']);
        $this->obj_site->obj_smarty->assign('desc', $_POST['tas_description']);
    }
} else {
    $this->obj_site->obj_smarty->assign('title', '');
    $this->obj_site->obj_smarty->assign('desc', '');
    unset($_POST);
}

bln_added is false by default, but changes to true once the form is successfully submitted. The smarty variables title and desc are used in the template to keep the form content there in case there is a user error and they need to change what they entered.

If the form is submitted successfully it sets bln_added = true, so the second bit of code should not only clear the form fields, but also empty $_POST. But if I press f5 the post data is still there.

Any ideas?

like image 458
wheresrhys Avatar asked Apr 06 '09 18:04

wheresrhys


1 Answers

Your method could work in theory, but there's a much easier way.

After submitting the form successfully, perform a redirect. It doesn't matter where to, but it'll clear the $_POST.

header('Location: http://www.example.com/form.php');

In your case, it sounds like you want to redirect to the page you're already on. Append a $_GET parameter to the URL if you want to display a confirmation message.

Hope this helps,

Tom

like image 156
Tom Wright Avatar answered Oct 05 '22 12:10

Tom Wright