0

Possible Duplicate:
What is the canonical way to determine commandline vs. http execution of a PHP script?

Is there some "conditional" tags in php for cronjob? What i want to make:

if(cron_job_executing_this_php_file)
{
do something
}
elseif($_SERVER['REMOTE_ADDR'] = "blah.bl.ah.bl")
{
do something
}

Can i do something like this?

Community
  • 1
  • 1
DzoniT
  • 155
  • 1
  • 1
  • 8
  • why not just make a separate php file for your cron job? – Scott M. Mar 02 '12 at 16:08
  • you might be able to if your crontab is able to send a $_GET variable 0 3 * * * sudo /usr/local/bin/myfile.php?cron=true – t q Mar 02 '12 at 16:16
  • Seems to be an exact duplicate of [Can PHP detect if its run from a cron job or from the command line?](http://stackoverflow.com/questions/190759/can-php-detect-if-its-run-from-a-cron-job-or-from-the-command-line) – Leigh Mar 02 '12 at 16:22

4 Answers4

2

You can use php_sapi_name(). It should return a different value from the command line (including, but not limited to, cron) than from say CGI or mod_php.

jpic
  • 32,891
  • 5
  • 112
  • 113
2

You can just add an arg to you PHP call inside you crontab:

0 1 0 0 0 php myscript.php from_cron

And then test for it in the script:

   foreach($argv as $value)
   {
      echo "$value\n";
   }

It's safer than to rely on the $SERVER super global.

Damien
  • 5,872
  • 2
  • 29
  • 35
2

Yes!

If you put in something as follows:

if (isset($_SERVER['REQUEST_METHOD'])) {
    // Do non-shell stuff here
} else {
   // Do shell stuff here
}
random_user_name
  • 25,694
  • 7
  • 76
  • 115
  • I think you should reverse your comments, do non-shell stuff if REQUEST_METHOD is set. – jpic Mar 02 '12 at 16:25
2

You can pass an argument into the php script from cron.

Something like

01 04 1 1 1 /path/to/my/script.php "fromcron"

Then your script.php can ask:

if($argv[1]=="fromcron").

You may have some index errors, so don't ask for $argv[1] unless you know it's going to have an element at index [1].

cyrusv
  • 247
  • 3
  • 15