views:

90

answers:

6

The title is quiet straightforward. I have to know on server side if the script called through HTTP request or by command line. I could examine the $_SERVER['argv'] or $_SERVER['argc'].
What is the pragmatic way to do that?

+1  A: 

Look at the keys in $_SERVER. If it is a cli request, you shouldn't see any that start with "HTTP".


Here is some simple test code:

<?php

foreach( $_SERVER as $k=>$v ){
    echo "$k: $v\n";
}

?>

And here is the output:

aj@mmdev0:~/so$ php cli.php |grep HTTP
aj@mmdev0:~/so$
AJ
No need for a loop when you can just test one single value.
kemp
@kemp, the OP's question specifically asked for alternatives to argc
AJ
+1  A: 

Possibly checking if no $_SERVER['HTTP_HOST'] is set? Because I believe that variable is populated through the Request Headers sent to a file on exection, and the command line probably doesn't send headers.

Chacha102
Ha, within 1 second of eachother...
AJ
A: 

You can check if the global variable $argc is set.

kemp
A: 

I suggest checking if(isset($_SERVER['SERVER_NAME']))

Traveling Tech Guy
I'm not sure that this isn't set. It might, especially if your are executing your PHP file remotely..
Chacha102
I think the $_SERVER array is reserved to HTTP transactions, but you might be right. It's still worth going through the various members in it as I'm sure they differ between local and remote execution.
Traveling Tech Guy
A: 

But you have to send the data through http (tcp) anyway no matter if the script is called from cli or from a browser

streetparade
You are just wrong.
erenon
+5  A: 

http://us3.php.net/manual/en/function.php-sapi-name.php

<?php
echo PHP_SAPI;
echo php_sapi_name();
?>
konforce
Well done, thanks.
erenon
+1 This is the way to go. I have had problems with checking $_SERVER variables and stuff like that. This one always works.
Pekka
+1 didn't know about this function, thanks!
AJ