Use Session tokens in php to prevent repeated submission of Ajax forms

Source: Internet
Author: User
There are two ways to prevent repeated form submission: 1) using redirection (non-Ajax form submission) 2) using SessionToken (Session token) there are two ways to prevent repeated form submission:

1) redirect (non-Ajax form submission)

2) use Session Token)

When the client requests a page, the server generates a random number, places the random number in the session, and sends the random number to the client. if the customer submits the request for the first time, the random number will be sent to the server. the server will receive the random number and compare it with the random number saved in the session. at this time, the values of the two are the same. the server considers it the first time to submit the random number, the random value of the server will be updated. if the request is submitted again at this time, the random number sent from the client to the server is the same as the previous one, and the random number sent from the server has changed. The two are different, the server considers this as a duplicate commit.

Generate a random number and use md5 for encryption:

$_token = md5(microtime()+rand(1,10000));$_SESSION['_token'] = $_token;

Send the value to the client and submit it as a hidden form field:

 

At the time of submission, the submitted data is compared with the data in the server Session. if it is null or not equal, the operation is considered invalid:

If (! Isset ($ _ POST ('_ token') {echo json_encode (array ('status' => 'failed', 'MSG' => 'Invalid operation! '); Exit ();} if (isset ($ _ POST [' _ token']) & $ _ POST ['_ token']! = $ _ SESSION ['_ token']) {echo json_encode (array ('status' => 'failed', 'MSG' => 'The form can only be submitted once, repeated submission is not allowed! '); Exit ();}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.