1

Possible Duplicate:
PHP - how to best determine if the current invocation is from CLI or web server?

I created a daily CRON job on my hosting server, which runs on UNIX, of course.

I put the following command in:

/usr/bin/php /home/myusername/public_html/foo/foo.php

And then, as expected, it executed this foo.php on a daily basis.

But this foo.php contains important information, and I don't want random people (not to be rude) going to http://www.mywebsite.com/foo/foo.php and executing the script.

So what can I do to differentiate between the CRON job, and a human user in PHP?

I've recently seen that when the CRON job is executed, no IP address is given ($_SERVER['REMOTE_ADDR'] is empty). But I'm not sure if that's a fluke.

I tried searching for this topic on Google, with no avail.

Community
  • 1
  • 1
Lucas
  • 16,930
  • 31
  • 110
  • 182

2 Answers2

3

You could just put the cron script outside of the web root, say in /home/myusername/cron.

Alternatively, if this is not an option due to FTP restrictions, you can add a parameter to the cron script:

/usr/bin/php /home/myusername/....../foo.php cron

Then check:

if( $_SERVER['argv'][0] != "cron") die("This is a cron script, you cannot access it.");
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
2

I've used this in the past

if (php_sapi_name() != "cli") {
    throw new Exception("someone tried to run this script outside of cli");
}

The php_sapi_name() function can tell you who's running the script. Here's the doc page: php_sapi_name

Lucas
  • 16,930
  • 31
  • 110
  • 182
Tobias Snoad
  • 320
  • 3
  • 9