By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,501 Members | 2,871 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,501 IT Pros & Developers. It's quick & easy.

CLI/web test

P: n/a
Hi,

Is there a recognised (ie. reliable) way for a script to test
if it is being run from the command line or through a web server ?

My guess whould have been :-

if (isset($_SERVER))

THEN it is being run from a web server.

But this may also be set when run through the CLI ?

Any suggestions ?

Thanks,
John.

Jul 17 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
John wrote:
My guess whould have been :-

if (isset($_SERVER))

THEN it is being run from a web server.

But this may also be set when run through the CLI ?


http://www.php.net/php_sapi_name returns 'cli' when the script is invoked on
the command line.
JW

Jul 17 '05 #2

P: n/a
John wrote:
Is there a recognised (ie. reliable) way for a script to test
if it is being run from the command line or through a web server ?
Try
http://www.php.net/php_sapi_name
My guess whould have been :-

if (isset($_SERVER))

THEN it is being run from a web server.

But this may also be set when run through the CLI ?


Yes, for me $_SERVER is set both for PHP CLI and PHP as a Apache module;
however its contents are different.

for example:
$_SERVER['SERVER_ADDR'] only exists for the module
$_SERVER['argc'] only exists for the CLI

--
Mail to my "From:" address is readable by all at http://www.dodgeit.com/
== ** ## !! ------------------------------------------------ !! ## ** ==
TEXT-ONLY mail to the whole "Reply-To:" address ("My Name" <my@address>)
may bypass my spam filter. If it does, I may reply from another address!
Jul 17 '05 #3

P: n/a
Janwillem Borleffs wrote:
John wrote:
My guess whould have been :-

if (isset($_SERVER))

THEN it is being run from a web server.

But this may also be set when run through the CLI ?

http://www.php.net/php_sapi_name returns 'cli' when the script is invoked on
the command line.


Thanks - I find that it returns 'cgi', but that will do.

John.

Jul 17 '05 #4

P: n/a
John wrote:
Janwillem Borleffs wrote:
John wrote:
My guess whould have been :-

if (isset($_SERVER))

THEN it is being run from a web server.

But this may also be set when run through the CLI ?

http://www.php.net/php_sapi_name returns 'cli' when the script is
invoked on the command line.

Thanks - I find that it returns 'cgi', but that will do.

John.

It probably depends on if you're using the CGI build or CLI build, as
both exist and both work slightly differently.

What I would do is simply test for a web-environment variable such as
$_SERVER['REQUEST_URI'].

if (isset($_SERVER['REQUEST_URI'])){
This is a web instance
}
else {
This is a CLI instance.
}
Jul 17 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.