1,使用HTTPS协议,如下例子
$url = 'https://api.example.com/endpoint';
$options = [
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
],
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
2,进行身份验证,例如
$api_key_str = 'str_num';
$url = 'https://www.www,com/user?api_key_str='.urlencode($api_key_str);
$res = file_get_contents($url);
3,进行API的访问次数限制,例如
$ip = $_SERVER['REMOTE_ADDR'];
$key = 'access_limit:' . $ip;
$redis = new Redis();
$redis->connect('127.0.0.1',6379);
$count->$redis->incr($key);//当前次数加1
$redis->ecpire($key,60);//设置过期秒数
if($count > 60) throw new customException('Access limit exceeded'); //抛出结果
$log_entry = date('Y-m-d H:i:s') . ' ' . $_SERVER['REQUEST_METHOD'] . ' ' . $_SERVER['REQUEST_URI'];// 记录访问日志
$redis->lpush('access_log', $log_entry);