PHP - Block External API Calls

人走茶凉 提交于 2019-12-11 13:09:38

问题


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

How can I do?

Thanks.


回答1:


You can just use this at the start of your API

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

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

Edit

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.

Ex.

$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
}


来源:https://stackoverflow.com/questions/36580917/php-block-external-api-calls

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!