dongpang1232 2017-01-27 13:59
浏览 11
已采纳

PHP - 如何限制API? [关闭]

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.

  • 写回答

1条回答 默认 最新

  • doutui2883 2017-01-27 14:13
    关注

    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!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退