PHP detect if its run from a cron job?

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