Technologies: PHP, MySQL
We were recently working on an internal project which had a segment in which it is required to limit form submission based on IP.
This is a brief case-study cum tutorial which describes how to limit IP based form submission with PHP and MySQL.
The Scenario To limit form submission based on IP
We have described the requirement of what needs to be achieved earlier. In addition to that the scenario which needs to be tackled was, that a user should be allowed to make only 5 submissions per hour.
The application for this project is being built on PHP and MySQL. So we decided to save the IP requests in a database table and calculate the time of submission and limit accordingly.
In the new MySQL table, the IP address from which the form was submitted and the current time-stamp when the form was submitted is being saved. The database is kept on updating when a form submission is made, provided the user has not exceeded the number of form submissions.
MySQL table structure
The MySQL table structure for logging the form submissions is created as follows.
The table consists of the following columns:
- ID (id): Which is a primary key and auto-increment
- IP Address (ip_address): A varchar datatype with a length of 256 bytes.
- Timestamp (timestamp): This is the default MySQL CURRENT_TIMESTAMP data type.
A PHP function was developed which would return the number of submissions that was made from an IP address in a specified amount of time. The IP address and the time interval is passed in the function as an argument. The PHP function is as follows
Now this function can be used and the IP address and time to restrict can be passed to get the count. This count can be then checked to restrict or allow the users to submit a form to do any action.
The code used to check the number of submissions and restricting form submission was as follows
This way, we are able to limit 5 form submission in 1 hour.
If there is a more efficient, different or an easy way to achieve this please feel free to share your thoughts in the comment form below
- SigNaL89s answer on StackOverflow