Get the Flash Player to see this player.
Logo Design by
Logo Design by FlamingText.com

quinta-feira, 27 de setembro de 2012

PHP detect if its run from a cron job?


Hits: 789  

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.

I was working on my favorite scraper program, that was working fine with browsers but failed on crontab. So, I need to run same script from both interfaces several times.

My Cron Job was working like

curl -s -o /dev/null http://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_sapi_name());print_r_to_file($_SERVER,dirname(__FILE__)."/logs/cli.txt");echo"
";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);}?>

View the original article here

Nenhum comentário:

Postar um comentário