Detect php cli execution

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
WaldoMonster
Forum Contributor
Posts: 225
Joined: Mon Apr 19, 2004 6:19 pm
Contact:

Detect php cli execution

Post by WaldoMonster »

I have a web-based script than I can manually update.
For the web interface you must login.
But I want the same script run as a scheduled cli script.
To defeat the login procedure it must reliable detect that the script is executed from the cli.
Is there a reliable way to detect if the script is executed from the cli?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

User avatar
WaldoMonster
Forum Contributor
Posts: 225
Joined: Mon Apr 19, 2004 6:19 pm
Contact:

Post by WaldoMonster »

Didn't you mean php_sapi_name() instead?
But this returned "cgi-fcgi" from the cli.
It could also be from a web server.

Detecting if one of the following values are set:

Code: Select all

$_SERVER['REQUEST_METHOD'];
$_SERVER['SERVER_PROTOCOL'];
$_SERVER['SERVER_PORT'];
Or is this not reliable?
Last edited by WaldoMonster on Thu Mar 22, 2007 7:42 pm, edited 1 time in total.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Err, yeah.. php_sapi_name(). If it says it's CGI then it's not the CLI version.

Often, the existence of $argv ($_SERVER['argv']) and $argc ($_SERVER['argc']) are decent detectors. Especially if you pass some data to the script when running it from the CLI.
User avatar
WaldoMonster
Forum Contributor
Posts: 225
Joined: Mon Apr 19, 2004 6:19 pm
Contact:

Post by WaldoMonster »

I found the right php.exe, in the cli map.
Now php_sapi_name() gives the expected result.
Thanks for the help.
Post Reply