PHP detect if its run from a cron job?

Hits: 3995  

I was looking for way to detect if PHP script was run from a shell (cron job), or if it was run from the browser.

My Cron Job was working like

* * * * * curl -s -o /dev/null


The best solution is to detect $_SERVER variable with a PHP script…

The first difference was “HTTP_USER_AGENT

[HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19  (On Browser)

[HTTP_USER_AGENT] => curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/ zlib/1.2.3 libidn/1.18 libssh2/1.2.2   (On CronTab)


$u_agent = $_SERVER[‘HTTP_USER_AGENT’];

// Mozilla Firefox

// curl cron

Try to review more differences 😉



header('Content-type: text/html; charset=utf-8');

debug_log(dirname(__FILE__)."/logs/cli.txt",implode(" ",$_SERVER));

debug_log(dirname(__FILE__)."/logs/cli.txt","CLI: ->".php_sapi_name());



/* print_r to File */

function print_r_to_file($var,$file){
    // writing response to external file

/* debug log */

function debug_log($file_path,$text)
    if(fwrite($handle,$text."\n")== FALSE )


Published by

Sandeep Verma

I’m an Entrepreneur. I’m proud to work as Blogger, LAMP Programmer, Linux Admin, Web Consultant, Cloud Manager, Apps Developer, Searcher. Concentrate > Observe > Imagine > Launch

One thought on “PHP detect if its run from a cron job?”

  1. But this is only working, when I start a URL (via CURL command) in the cronjob – when you start only a file (via PHP command), this doesn´t work due the missing $_SERVER enviroment. Alternate, when you want to use a PHP command (which should be prefered) you can add a parameter in your cronjob, which you can check in the PHP as argument value.

Leave a Reply

Your email address will not be published.