简体   繁体   中英

How to prvent multiple and fast post request to a php script

I have a controller in codeigniter which is called by Ajax from UI, on normal actions from UI every thing is good and this is what happens in the script, this is just a demo code not real (just want to show what happens):

$uid=$_POST['uid'];
$id=$_POST['id'];
$bank=load_bank($uid,$id); // Load Bank From MySql DB

add_to_user_balance($uid,$bank['amount']); // "Add" the bank's amount to user balance in DB

zero_bank_amount($uid,$id); // Reset the bank amount to zero

In 2 normal UI calls (which are called 1s after each other):

  • In the first call $bank['amount'] is 1000 (for example). It is added to user's balance and is set to 0
  • In the second call $bank['amount'] is 0 as it was set to 0 in last call, so nothing is added to the balance

But, some spammers/hackers uses some bots or any thing else to call this controller very fast. For example suppose that this script is called 2 times instantly (for example less than 200ms):

  • In the first call $bank['amount'] is 1000 (for example). It is added to user's balance and is set to 0
  • In the second call $bank['amount'] is not 0 because the first call still working and didn't set the $bank['amount'] to 0 as it didn't have enough time before second call

Do you have any method to prevent these kind of fast calls? for example restrict user to have 1s gap between each call?

Use some locking of your choice.

A few possibilities (and there are many many more):

  1. filesystem: Create some file in a temp directory with a name like lockfile_uid, where uid is the unique userid. Before starting any transaction, check for the existance of this file, if it exists, don't do anything, or create an error. If it doesn't exist, you create the file on start of your script, and delete it when you finish.

  2. Database: create a table with the same purpose with uid's. Same logic as above

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM