2

Is there any way I can detect if my script is being run via a Cron Job or via Browser? Is there any specific cron job http header or user agent?

Edit: I am just trying to make a script which can be run directly (via URL) and can also be scheduled as cron job. Whenever executed, I just want to detect if the script is being run by a cron job and do some stuff in a condition.

arxoft
  • 1,385
  • 3
  • 17
  • 34
  • Can you share your code or give some other info of how and what are you trying.... – ankur140290 Feb 06 '14 at 05:03
  • I edited the Question to be more clear. – arxoft Feb 06 '14 at 05:08
  • @aceph try my answer on your php page – Satish Sharma Feb 06 '14 at 05:09
  • you can detect via different methods , if you have detect only for confirmation that cron job file is executed or not then you may try to send mail for confirmation on cron success execution. – user12 Feb 06 '14 at 05:20
  • I would var_dump($_SERVER) to a log file from each and compare. Seems to me results are going to vary between server configs and what command you decide to use in cron to trigger the script (php, curl, wget?). – John McMahon Feb 06 '14 at 05:21

2 Answers2

1

There is a php_sapi_name() function for that

zerkms
  • 249,484
  • 69
  • 436
  • 539
-1

you can check it like this

if(isset($_SERVER['SERVER_NAME']))
{
     // running through browser
}
else
{
    // running through cron
}
Satish Sharma
  • 9,547
  • 6
  • 29
  • 51
  • Not sure why this has been voted down - it'd be nice to see some feedback, so we could know if there's a reason it's a bad idea. Works pretty well in my scenario (although I've used SERVER_ADDR for convenience) – Dazbert Oct 04 '22 at 19:36