0

I am having a script which can be launched with either cron, HTTP request (browser) or from another script. How can I determine from where a script was launched?

Eugeny89
  • 3,673
  • 7
  • 49
  • 94
  • I think you can find a solution in this post http://stackoverflow.com/questions/1854297/how-to-determine-if-a-php-file-is-loaded-via-cron-command-line – JimboSlice May 20 '15 at 08:43
  • Also have a look at this function [`php_sapi_name()`](http://php.net/manual/en/function.php-sapi-name.php). It hold's the sapi handler name. So if you run the script by CLI this function returns `cli`. If you run it from a fast-cgi instance you get `cgi-fcgi` and so on. – TiMESPLiNTER May 20 '15 at 08:45

3 Answers3

1

You can check a few pieces of information to find out:

The constant PHP_SAPI will tell you which PHP interpreter/interface is running - the names of common SAPI's are documented on the page for php_sapi_name

For command line scripts, you should be able to achieve what you want my using a combination of the posix_isatty function and checking for the existence of $_SERVER['TERM']

Stephen
  • 17,981
  • 4
  • 30
  • 31
0

The most simple way to solve this is to pass an argument to your script. This will give you high control over the format of the information and it is (reasonably) safe.

Burki
  • 1,178
  • 21
  • 26
0

Not sure, is this what you wanted ..

Cron:

php -q /dir/my_script.php cron

HTTP:

http://dir/my_script.php?arg=web

PHP:

if (!empty($argv[0])) 
{
    echo "local";
} 
elseif(isset($_GET['arg']))
{
    echo "web";
}
else
{
    echo "Others"
}
Makesh
  • 1,230
  • 1
  • 11
  • 24