How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

后端 未结 23 1282
醉话见心
醉话见心 2020-11-22 00:46

I have a simple form that submits text to my SQL table. The problem is that after the user submits the text, they can refresh the page and the data gets submitted again with

23条回答
  •  离开以前
    2020-11-22 01:27

    A refined version of Moob's post. Create a hash of the POST, save it as a session cookie, and compare hashes every session.

    // Optionally Disable browser caching on "Back"
    header( 'Cache-Control: no-store, no-cache, must-revalidate' );
    header( 'Expires: Sun, 1 Jan 2000 12:00:00 GMT' );
    header( 'Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT' );
    
    $post_hash = md5( json_encode( $_POST ) );
    
    if( session_start() )
    {
        $post_resubmitted = isset( $_SESSION[ 'post_hash' ] ) && $_SESSION[ 'post_hash' ] == $post_hash;
        $_SESSION[ 'post_hash' ] = $post_hash;
        session_write_close();
    }
    else
    {
        $post_resubmitted = false;
    }
    
    if ( $post_resubmitted ) {
      // POST was resubmitted
    }
    else
    {
      // POST was submitted normally
    }
    

提交回复
热议问题