erenon
erenon

Reputation: 19118

How to differentiate between http and cli requests?

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?

Upvotes: 11

Views: 4303

Answers (6)

Matthew
Matthew

Reputation: 48284

https://www.php.net/manual/en/function.php-sapi-name.php

<?php
echo PHP_SAPI;
echo php_sapi_name();
?>

Upvotes: 14

streetparade
streetparade

Reputation: 32878

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

Upvotes: 0

Traveling Tech Guy
Traveling Tech Guy

Reputation: 27811

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

Upvotes: 0

Matteo Riva
Matteo Riva

Reputation: 25060

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

Upvotes: 0

Tyler Carter
Tyler Carter

Reputation: 61547

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.

Upvotes: 1

AJ.
AJ.

Reputation: 28174

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$

Upvotes: 2

Related Questions