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

查看:37
本文介绍了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天全站免登陆