繁体   English   中英

如何将api请求计数存储到PHP脚本以快速回复客户端?

[英]How to store api request count to a PHP script for fast reply to the client?

我最近在这里问: 如何知道哪个网站要求php提供外部图像?

第三方网站请求如下图像:

<img src="http://www.myserver.com/mypage.php?api=APIKEY&text=some-text-here" alt=""/>

我需要每小时和每天限制特定api密钥的访问权限。

现在我在mysql DB上存储了一些数据:

id,apikey,limit_ip,limit_referer,limit_hour,limit_day

1,JFKHJSDLGHUFIE,127.0.0.1,*,250,10000

<?php

//Verify Referer
if(
    !isset($_SERVER['HTTP_REFERER']) || $_SERVER['HTTP_REFERER'] == "" ||
    !isset($_GET['apik']) || $_GET['apik'] == "" ||
    !isset($_SERVER['REMOTE_ADDR']) || $_SERVER['REMOTE_ADDR'] == "") {
        exit("API error, your referer informations aren't set");
} else {
    //Site referer
    $site = $_SERVER['HTTP_REFERER'];
    //Ip referer
    $ip = $_SERVER['REMOTE_ADDR'];
    //Get api key
    $apik = htmlentities($_GET['apik']);

    try
    {
        $options = array(
            PDO::MYSQL_ATTR_INIT_COMMAND    => "SET NAMES utf8"
        );
        //MySQL connection
        $bdd = new PDO('mysql:host=localhost;dbname=apitest', 'root', '', $options);
    }
    catch(Exception $e)
    {
        //If error, die
        die('Error: '.$e->getMessage());
    }


    //Lookup for the apikey in the database
    $answer = $bdd->query('SELECT * FROM apiCode WHERE apikey = "'.$apik.'" LIMIT 0,1');
    //Fetch settings for this api key
    while ($data = $answer->fetch()) {
        $limit_ip = $data['limit_ip'];
        $limit_referer = $data['limit_referer'];
        $limit_hour = $data['limit_hour'];
        $limit_day = $data['limit_day'];
    }

    //Verify API limits
    //Cookie, session, database? 


    //Return content
    echo "Api : Success!";

}

我认为最好的方法是在数据库中创建一个表,如:

id,access_hour,access_day

使用cron作业等每小时重置access_hour字段,但是服务内容将花费更多的时间,因为MySQL非常懒散,如果它快速:)它会更好。

Cookie将存储在远程计算机上,因此不可靠。

会话的持续时间为15分钟......因此存储和限制访问时间太短。

以上所有陈述仅来自我的观点。

我的问题是:如何在不影响服务速度的情况下每小时和每天存储和限制特定API密钥的访问次数?

  • 没有:它只需要快速可靠。

我不会把这些数据放在mysql中。 您不需要耐久性或持久性来获取此类信息。 使用memcached会更好,并使用如下算法:

http://en.wikipedia.org/wiki/Leaky_bucket

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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