php 只接受来自本地主机的获取/发布请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9872751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:50:05  来源:igfitidea点击:

Accepting get/post requests only from localhost

phpajaxcodeigniterpostget

提问by Alex

Because the data size isn't little that my web app needs to load, it gets pretty slow some times so therefor I decided to add some jQuery ajax functions to load certain data upon request and then save it in a cache.

因为我的 web 应用程序需要加载的数据大小不小,有时它会变得很慢,因此我决定添加一些 jQuery ajax 函数来根据请求加载某些数据,然后将其保存在缓存中。

What I would like to know is how can I limit any GETor POSTrequests only from localhost/same server/same ip so I can avoid any calls from outside to my app?

我想知道的是如何限制来自本地主机/相同服务器/相同 ip 的任何GETPOST请求,以便我可以避免从外部对我的应用程序进行任何调用?

That means that my php functions that returns data, should return data only if requested from localhost.

这意味着我的 php 函数返回数据,只有在从本地主机请求时才应该返回数据。

My web app runs on CodeIgniter's framework and my web server's configuration is a LAMP running on ubuntu.

我的 Web 应用程序在 CodeIgniter 的框架上运行,而我的 Web 服务器的配置是在 ubuntu 上运行的 LAMP。

Any ideas?

有任何想法吗?

回答by gorelative

in the constructor you could use

在您可以使用的构造函数中

if ($_SERVER['SERVER_ADDR'] != $_SERVER['REMOTE_ADDR']){
  $this->output->set_status_header(400, 'No Remote Access Allowed');
  exit; //just for good measure
}

However if this method isnt what you're looking for.. use .htaccessyou can perform a quick google search to return a specific example for denying get/post to all and then allow for 127.0.0.1/localhost.

但是,如果此方法不是您要查找的方法.. 使用.htaccess您可以执行快速谷歌搜索返回一个特定示例,以拒绝向所有人获取/发布,然后允许 127.0.0.1/localhost。

回答by h00ligan

Using .htaccess is probably the best way, allow only from your local address and 127.0.0.1. I found this example at petergasser.comand changed it only slightly:

使用 .htaccess 可能是最好的方法,只允许来自您的本地地址和 127.0.0.1。我在petergasser.com 上找到了这个例子,并且只是稍微改变了它:

AuthName "bla"  
AuthType Basic  
<Limit GET POST>  
order deny,allow  
deny from all 
allow from 127.0.0.1
allow from <your-ip-here>
</Limit>  

回答by slash197

Use a key (think of API keys) to send along the request to your server. Then on your server you check that key and if it's the right one you return data.

使用密钥(想想 API 密钥)将请求发送到您的服务器。然后在您的服务器上检查该密钥,如果它是正确的,则返回数据。

回答by Fathur Rohim

I use like this, thanks to @gorelative

感谢@gorelative,我是这样使用的

if( 
isset($_SERVER['REMOTE_ADDR']) AND ( $_SERVER['REMOTE_ADDR'] !== $_SERVER['SERVER_ADDR'] )
){
 die(' Access Denied, Your IP: ' . $_SERVER['REMOTE_ADDR'] );
}