1

So I need to make a cron job that runs every 24 hours and sends out some emails. I need to do it in a way, that only server is able to run it, and it needs to be in CodeIgniter.

So lets suppose that I have it in controller called cron.php, how do I make it that only server can execute it. So far i have thought of putting something like this in the constructor:

if($_SERVER['SERVER_ADDR'] != $SERVER['REMOTE_ADDR']){
    //kill the script, do not send emails
}

So my question is, this seems too simple, Can these values be spoofed/manipulated somehow? Is it hard to do?

Is there any better ways to approach this (Short of making this as a standalone program hidden somewhere outside the public web-root?

galdikas
  • 1,609
  • 5
  • 19
  • 43
  • Can we know exactly why only the server should run this? There might be other/better solutions possible... – Salketer Jul 18 '14 at 12:17
  • 1
    As one of possible methods, you can check `$argc/$argv` global variables – hindmost Jul 18 '14 at 12:20
  • @Salketer, because I want to set it up that server runs the cronjob ever 24hrs. If anyone but server itself can run the script then someone could go to: example.com/cron, and execute the script sending out the emails. – galdikas Jul 18 '14 at 13:30
  • Then, the best way to do it is use a timestamp in a file or database. Update it every time the script is ran, and make sure to run the script only is the saved timestamp is 24hours old. – Salketer Jul 21 '14 at 08:52
  • this is actually very clever. Even if someone was to run it, they could only run it every 24 hours. Simple, but brilliant really. – galdikas Jul 21 '14 at 09:09
  • Too bad nobody answered the "seems too simple" part of the question. Looks like it is not safe, as there are ways to [forge REMOTE_ADDR](http://stackoverflow.com/questions/5092563/how-to-fake-serverremote-addr-variable). – alx Aug 25 '15 at 20:24

1 Answers1

2

A way to add some "security" is by implementing a sort of API key that is required to execute the script.

Your cron would fetch an URL like

https://server/.../cron.php?key=<random string here>

Make sure you keep the key secret.

Othi
  • 336
  • 1
  • 6
  • I was thinking of that as well. But wouldn't 3rd party be able to monitor the traffic, and see the requests coming in to the server? – galdikas Jul 18 '14 at 13:29
  • Not if you're fetching over HTTPS. – Othi Jul 18 '14 at 13:33
  • Nah no HTTPS at the moment. But we will probably be getting it. I suppose I will add this as an extra mesure on top of the IP check :) – galdikas Jul 18 '14 at 14:44