I have a custom api page. How can I limit the number of requests by IP address?
I need some examples in PHP, I'm not too experienced with this.
I'm running an apache2 server.
I have a custom api page. How can I limit the number of requests by IP address?
I need some examples in PHP, I'm not too experienced with this.
I'm running an apache2 server.
You could get the IP of the person who called the API and upload it into a database inserting the IP and the time of the submission. Then, at the top of you API page, verify if the IP of the visitor (I'm not sure if this will work with cURL, but you could just use $_SERVER['remote_addr']) and if it is stored on the database, verify if is passed something like an hour from the submission. In this case, you can delete the record. If not, let the visitor make the API call and insert its IP into the database.
<?php
$conn = new mysqli(host,user,password,database);
$sql = "SELECT * FROM ip";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
if($row['ip'] == VISITOR'S IP) {
--GET THE TIME OF THE IP SUBMISSION--
if($time > 1hour) {
$sql = "DELETE FROM ip WHERE ip="$row['ip'];
--LET API WORK--
}
}
}
$sql = "INSERT INTO ip (ip) VALUES (--VISITOR'S IP--)";
$result = $conn->query($sql);
if(!$result) {
echo "SQL Error : ".$sql."<br> Error : ".$conn->error;
}
else {
$conn->close();
}
?>
I hope this will help you. Cheers!