2

I'm doing something like this now:

if (empty($_SERVER['SERVER_NAME'])) {
  // the script is run by a Cron job
} else {
  // the script is run by a HTTP request
}

Will it go wrong at some situation? More specifically, is $_SERVER['SERVER_NAME'] always set by Apache? I know some of the variables in $_SERVER like $_SERVER['REMOTE_ADDR'] could be tainted by the client side.

Any advice?

Boon Kgim
  • 56
  • 4
  • 1
    possible duplicate of [What is the canonical way to determine commandline vs. http execution of a PHP script?](http://stackoverflow.com/questions/173851/what-is-the-canonical-way-to-determine-commandline-vs-http-execution-of-a-php-s) – Jon Mar 01 '12 at 10:51
  • 1
    I tried the suggested answer of using php_sapi_name() for the question but both Cron and HTTP request return the same value of 'cgi'. – Boon Kgim Mar 01 '12 at 10:55
  • How are you making your cron call? with something like `wget http://blah/script.php` or `php script.php`? – Leigh Mar 01 '12 at 10:58
  • 1
    Then I'm very very surprised that `php_sapi_name` or `PHP_SAPI` are anything other than `cli` – Leigh Mar 01 '12 at 11:07
  • Just tested. crontab with `*/1 * * * * php /path/to/script.php` outputs `cli` with `php_sapi_name()`. – Leigh Mar 01 '12 at 11:14
  • Think php_sapi_name() could be depending on server installation. I tested on my server but both output cgi – Boon Kgim Mar 01 '12 at 11:33

2 Answers2

0

Try inbuilt php function php_sapi_name It returns the type of interface between web server and PHP

or else, you can use

__FILE__   with dirname(__FILE__) or 
$_SERVER['SCRIPT_NAME']

to identify the path name of the current executing php script. Store this in a variable, and apply linux grep command to verify whether it exists in the cron location /usr/etc/crontab

Swatantra Kumar
  • 1,324
  • 5
  • 24
  • 32
0

Make two separate scripts would be my first suggestion.

Also $_SERVER['SERVER_NAME'] depends on the server setup, but should always be set.

From Apache Docs:

If no ServerName is specified, then the server attempts to deduce the hostname by performing a reverse lookup on the IP address. If no port is specified in the ServerName, then the server will use the port from the incoming request. For optimal reliability and predictability, you should specify an explicit hostname and port using the ServerName directive.

Ingmar Boddington
  • 3,440
  • 19
  • 38
  • Hmm... separate script would defeat the purpose of what I'm trying to do. I'm actually trying to use the HTTP request for the convenience of debugging the script. Previously I tried changing the script manually to affect only test data during debugging but I find it inconvenient as sometimes I forgot to change it back to the actual script. – Boon Kgim Mar 01 '12 at 11:09
  • Then maybe have the file in your webroot for debugging and move it out / remove debugging when switching to a cronjob – Ingmar Boddington Mar 01 '12 at 11:22