Differences between CLI and CGI
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,CLIdoes not write any headers to the output by default. - There are some
php.inidirectives that are overridden inCLI SAPIbecause they are meaningless in a shell environment: html_errors: CLI defaults toFALSE.implicit_flush: default CLI value isTRUEmax_execution_time: default CLI value is0(unlimited)register_argc_argv: default CLI value isTRUE- The script can take command line arguments! The
$argcvariable gives you the number of arguments passed to the application. And the$argvfield 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,STDINis a file handler forfopen('php://stdin', 'r'). So you can read a line fromSTDINlike this:$strLine = trim(fgets(STDIN));. TheSTDINis 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-winnothing is printed, and thus provides no console (no "dos box" is displayed on the screen). This behaviour is similar toPHP GTK.