我们使用CodeIgnitor PHP框架制作了网站。我们运行一个cron作业,用它来点击URL。
但有了这个URL,就可以从任何一台机器上点击它,因为它的功能是执行与数据库相关的任务。
我们想让该功能只在服务器IP或特定IP列表中命中,这样我们才能添加允许的机器才能命中该URL?
我们该怎么做?
也许你应该使用.htaccess文件?(如果使用Apache)文档:http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html
<Directory /www>
Order Deny,Allow
Deny from all
Allow from YOUR_IP
</Directory>
在PHP中,您可以在脚本的顶部执行以下操作:
$allow = array("123.456.789", "456.789.123", "789.123.456"); //allowed IPs
if(!in_array($_SERVER['REMOTE_ADDR'], $allow) && !in_array($_SERVER["HTTP_X_FORWARDED_FOR"], $allow)) {
header("HTTP/1.0 404 Not Found");
exit();
}
您可以对apache或nginx使用限制。这样会更安全。
对于nginx
location /path/to {
allow 192.168.1.1/24;
allow 127.0.0.1;
deny 192.168.1.2;
deny all;
}
对于apache
<Location /path/to>
Order deny,allow
deny from all
allow from 192.168.
allow from 104.113.
</Location >
Apache和Nginx
如果我是你,我会为CLI请求或管理员方法设置扩展条件。CI3
<?php if !defined('BASEPATH') exit('No direct script access allowed!');
class Cronjob extends CI_Controller
{
public function __construct()
{
if (!is_cli() && !is_admin()) {//assuming you have some login/checking module for admin
redirect('welcome', 'refresh')
}
}
public function index()
{
//your code here
}
}
CI2
<?php if !defined('BASEPATH') exit('No direct script access allowed!');
class Cronjob extends CI_Controller
{
public function __construct()
{
if (!$this->input->is_cli_request() && !is_admin()) {//assuming you have some login/checking module for admin
redirect('welcome', 'refresh')
}
}
public function index()
{
//your code here
}
}
为了解释这一点:CLI检查(检查CodeIgniter输入类/库)将允许服务器通过cronjob进行访问,检查管理员是否也允许授权用户通过该控制器进行调用。所以你不必为IP而烦恼,因为授权人员甚至可以在其他地方进行cron工作。换句话说,任何不是SERVER
或管理员的人都不能调用此controller/method
。