Differences between CLI and CGI
📅 15. 10. 2021
PHP can run in different environments. The most common environment is CGI
, which runs when PHP processes an HTTP request. However, it is also possible to run a PHP script from the Terminal, in which case it is a so-called CLI (Command-line interface) task.
The most important differences between CLI and CGI
- Unlike
CGI SAPI
,CLI
does not write any headers to the output by default. - There are some
php.ini
directives that are overridden inCLI SAPI
because they are meaningless in a shell environment:-
html_errors
: CLI defaults toFALSE
. -
implicit_flush
: default CLI value isTRUE
-
max_execution_time
: default CLI value is0
(unlimited) -
register_argc_argv
: default CLI value isTRUE
-
- The script can take command line arguments! The
$argc
variable gives you the number of arguments passed to the application. And the$argv
field gives you an array of actual arguments - There are 3 new constants defined for the shell environment:
STDIN
,STDOUT
,STDERR
. All are file handlers for the corresponding shell device. For example,STDIN
is a file handler forfopen('php://stdin', 'r')
. So you can read a line fromSTDIN
like this:$strLine = trim(fgets(STDIN));
. TheSTDIN
is already defined for you using thePHP CLI
. - The PHP CLI does not change the current directory to the directory of the script being executed. The current directory for the script would be the directory in which you run the PHP CLI command.
- There are a number of USEFUL options available for the PHP CLI. Which allow you to get some valuable information about your php setup, your php script or run it in different modes.
- In PHP 5 there have been some changes to the CLI and CGI file names. In PHP 5, the CGI version has been renamed to
php-cgi.exe
(formerlyphp.exe
) and the CLI version is now located in the main directory (formerlycli/php.exe
). - A new mode has also been introduced in PHP 5:
php-win.exe
. This is equivalent to the CLI version, except that inphp-win
nothing is printed, and thus provides no console (no "dos box" is displayed on the screen). This behaviour is similar toPHP GTK
.
Jan Barášek More about the author
The author works as a senior developer and software architect in Prague (Czech republic, Europe). He designs and manages large web applications that you know and use. Since 2009 he has gained a wealth of experience which he passes on through this website.
I'd be happy to help:
Contact