Reputation: 1525
I am running a PHP script via linux cronjob and I want to make sure that it can be run remotely only from the computer whose ip address I specify, plus via cronjob.
Now, I can check the remote ip addresses from $_SERVER['REMOTE_ADDR']
, but doing so would also stop execution via cronjob.So, how to make both things work?
Upvotes: 3
Views: 914
Reputation: 57316
You can use php_sapi_name
function to check for local (cron) execution in addition to checking IP addresses, something like this:
if (php_sapi_name() == 'cli' || $_SERVER['REMOTE_ADDR'] == 'xxx.yyy.zzz.vvv') {
//do your stuff
}
else {
/show some error
}
That said, you need to remember that remote address can be easily spoofed, therefore it's not good to rely on it, at least if the server is open to the internet. It's a bit more secure if you're running on a local network.
Upvotes: 1
Reputation: 2418
You'll need to check if it is run from the command-line too to handle the cron case
if (php_sapi_name() == 'cli' || $_SERVER['REMOTE_ADDR'] == 'your.ip.add.ress') {
// allow
}
Upvotes: 3
Reputation: 27295
Put the cronjob out of your web root.
Then you can check wheather the cron is running over a cli:
if (php_sapi_name() != 'cli') {
die();
}
Its no good idea to tun your cron over your webserver. Then every people can start it.
Upvotes: 3