PHP-阻止外部API调用 [英] PHP - Block External API Calls

查看:86
本文介绍了PHP-阻止外部API调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的网站上使用PHP创建了一个API

I've created an API in my site in PHP

现在,我想保护它,因为我不希望其他站点和/或用户可以从不是我的网站上调用它

Now I want to protect it because I don't want that other sites and/or users can call it from a website that it isn't mine

只能在我的网站上拨打电话

The calls can be made only from my site

我该怎么办?

谢谢.

推荐答案

您可以在API的开头使用它

You can just use this at the start of your API

if($_SERVER['REMOTE_ADDR'] != '127.0.0.1'){
    die;
}

它将杀死所有未从您的服务器调用的API尝试.

It will kill any API attempts that aren't being called from your server.

修改

或者,如果您希望用户能够调用API,则可以为他们提供一个API密钥,该密钥将存储在数据库中.

Or if you want users to be able to call the API, you can gave them an API key, that you will store in your database.

例如.

$con = mysqli_connect("localhost","my_user","my_password","my_db");
$key = mysqli_real_escape_string($con, $_GET['key']);
$search = mysqli_query("SELECT * FROM user WHERE api_key = '$key'");
if(mysqli_num_rows($search)==0){
    // kill the request
    die;
}
else{
    // Allow the request and do your business
}

这篇关于PHP-阻止外部API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆