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 https://www.svnlabs.com/allcron.php

 

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/3.13.1.0 zlib/1.2.3 libidn/1.18 libssh2/1.2.2   (On CronTab)

 

$u_agent = $_SERVER[‘HTTP_USER_AGENT’];

if(preg_match(‘/Mozilla/i’,$u_agent))
{
// Mozilla Firefox
}

if(preg_match(‘/curl/i’,$u_agent))
{
// curl cron
}

Try to review more differences 😉

 

<?php
error_reporting(E_ALL^E_NOTICE^E_WARNING);
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($_SERVER,dirname(__FILE__)."/logs/cli.txt");
echo"<pre>";
print_r($_SERVER);
/* print_r to File */
function print_r_to_file($var,$file){
    // writing response to external file
    $f=fopen($file,'w');
    ob_start();
    print_r($var);
    $return=ob_get_contents();
    ob_end_clean();
    fwrite($f,$return);
    fclose($f);
}
/* debug log */
function debug_log($file_path,$text)
{
    $file_dir=dirname($file_path);
    if(!file_exists($file_dir)or!is_dir($file_dir)or!is_writable($file_dir))
        returnfalse;
    
    $write_mode='w';
    if(file_exists($file_path)&&is_file($file_path)&&is_writable($file_path))
        $write_mode='a';
    
    if(!$handle=fopen($file_path,$write_mode))
        returnfalse;
    
    if(fwrite($handle,$text."\n")== FALSE )
        returnfalse;
    
    @fclose($handle);
}
?>