Tutorial by Examples

Arguments are passed to the program in a manner similar to most C-style languages. $argc is an integer containing the number of arguments including the program name, and $argv is an array containing arguments to the program. The first element of $argv is the name of the program. #!/usr/bin/php p...
When run from the CLI, the constants STDIN, STDOUT, and STDERR are predefined. These constants are file handles, and can be considered equivalent to the results of running the following commands: STDIN = fopen("php://stdin", "r"); STDOUT = fopen("php://stdout", "...
The exit construct can be used to pass a return code to the executing environment. #!/usr/bin/php if ($argv[1] === "bad") { exit(1); } else { exit(0); } By default an exit code of 0 will be returned if none is provided, i.e. exit is the same as exit(0). As exit is not a ...
Program options can be handled with the getopt() function. It operates with a similar syntax to the POSIX getopt command, with additional support for GNU-style long options. #!/usr/bin/php // a single colon indicates the option takes a value // a double colon indicates the value may be omitted ...
The function php_sapi_name() and the constant PHP_SAPI both return the type of interface (Server API) that is being used by PHP. They can be used to restrict the execution of a script to the command line, by checking whether the output of the function is equal to cli. if (php_sapi_name() === 'cli')...
On either Linux/UNIX or Windows, a script can be passed as an argument to the PHP executable, with that script's options and arguments following: php ~/example.php foo bar c:\php\php.exe c:\example.php foo bar This passes foo and bar as arguments to example.php. On Linux/UNIX, the preferred me...
When running from the CLI, PHP exhibits some different behaviours than when run from a web server. These differences should be kept in mind, especially in the case where the same script might be run from both environments. No directory change When running a script from a web server, the current w...
As from version 5.4, PHP comes with built-in server. It can be used to run application without need to install other http server like nginx or apache. Built-in server is designed only in controller environment for development and testing purposes. It can be run with command php -S : To test it cr...
This example shows the behaviour of getopt when the user input is uncommon: getopt.php var_dump( getopt("ab:c::", ["delta", "epsilon:", "zeta::"]) ); Shell command line $ php getopt.php -a -a -bbeta -b beta -cgamma --delta --epsilon --zeta --zeta=f...

Page 1 of 1