Accepting get/post requests only from localhost

2020-02-08 06:23发布

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.

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

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

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

Any ideas?

4条回答
smile是对你的礼貌
2楼-- · 2020-02-08 06:51

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.

查看更多
劳资没心,怎么记你
3楼-- · 2020-02-08 06:51

I use like this, thanks to @gorelative

if( 
isset($_SERVER['REMOTE_ADDR']) AND ( $_SERVER['REMOTE_ADDR'] !== $_SERVER['SERVER_ADDR'] )
){
 die(' Access Denied, Your IP: ' . $_SERVER['REMOTE_ADDR'] );
}
查看更多
太酷不给撩
4楼-- · 2020-02-08 06:54

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 .htaccess you 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.

查看更多
一纸荒年 Trace。
5楼-- · 2020-02-08 07:02

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

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>  
查看更多
登录 后发表回答