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?
views:
90answers:
6
+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
2010-01-31 19:27:25
No need for a loop when you can just test one single value.
kemp
2010-01-31 19:35:37
@kemp, the OP's question specifically asked for alternatives to argc
AJ
2010-01-31 19:40:54
+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
2010-01-31 19:27:26
I'm not sure that this isn't set. It might, especially if your are executing your PHP file remotely..
Chacha102
2010-01-31 19:29:38
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
2010-01-31 19:41:33
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
2010-01-31 19:29:11
+5
A:
http://us3.php.net/manual/en/function.php-sapi-name.php
<?php
echo PHP_SAPI;
echo php_sapi_name();
?>
konforce
2010-01-31 19:29:23