Abdullah Siddique
Abdullah Siddique

Reputation: 63

Allow the URL to be hit from allowed IPs machines only in PHP?

We have site made using CodeIgnitor PHP framework. We run a cron job to hit a URL with it.

But with that URL it can be hit from any machine as it's function made that does task related to database.

We want to make that function to be hit only within server IP OR specific IPs list so only that we will add our allowed machines can hit that URL?

How we can do that?

Upvotes: 0

Views: 2178

Answers (3)

Tpojka
Tpojka

Reputation: 7111

If I were you I would make extended condition for CLI request or let's say admin approach. 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
    }
}

To explain this: CLI checking ( check CodeIgniter Input class/library ) will allow server to approach through cronjob, and checking if admin will allow authorized user to make call over that controller as well. So you don't bother with IP because authorized person can make cron job even from other locations. In other words, anyone that is not SERVER or admin couldn't call this controller/method.

Upvotes: 0

fdglefevre
fdglefevre

Reputation: 692

Maybe you shoud use a .htaccess file ? (if you use Apache) Doc: 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>

In PHP you can do this on top of your script:

$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();
}

Upvotes: 1

mim.
mim.

Reputation: 677

You can use restriction over your apache or nginx. And this will be safer.

For nginx

location /path/to {
    allow 192.168.1.1/24;
    allow 127.0.0.1;
    deny 192.168.1.2;
    deny all;
}

For apache

<Location /path/to>
    Order deny,allow
    deny from all
    allow from 192.168.
    allow from 104.113.
</Location >

Apache and Nginx

Upvotes: 0

Related Questions