所有的PHP发行版,不论是编译自源代码的版本还是预创建的版本,都在默认情况下带有一个PHP可执行文件。这个可执行文件可以被用来运行命令行的PHP程序。
shell> /path/to/php -v
PHP 5.0.0 (cli) (built: Jun 1 2005 18:32:10)
Copyright (c) 1997-2004 The PHP Group
Zend Engine v2.0.0, Copyright (c) 1998-2004 Zend Technologies
它应该会返回PHP的版本号。
一个简单的PHP CLI程序
<?php
echo "Hello from the CLI";
?>
shell> /path/to/phphello.php
Hello from the CLI
使用标准的输入和输出
表格A
常量 | 说明 |
STDIN | 标准的输入设备 |
STDOUT | 标准的输出设备 |
STDERR | 标准的错误设备 |
列表A
<?php
// ask for input
fwrite(STDOUT, "Enter your name: ");
// get input
$name = trim(fgets(STDIN));
// write input back
fwrite(STDOUT, "Hello, $name!");
?>
Look what happens when you run it:
shell> /path/to/phphello.php
Enter your name: Joe
Hello, Joe!
使用命令行自变量
列表B
<?php
print_r($argv);
?>
Run this script by passing it some arbitrary values, and check the output:
shell> /path/to/phptest.php chocolate 276 "killer tie, dude!"
Array
( [0] => test.php
[1] => chocolate
[2] => 276
[3] => killer tie, dude!
)
列表C
<?php
// check for all required arguments
// first argument is always name of script!
if ($argc != 4) {
die("Usage: book.php <check-in-date> <num-nights> <room-type> ");
}
// remove first argument
array_shift($argv);
// get and use remaining arguments
$checkin = $argv[0];
$nights = $argv[1];
$type = $argv[2];
echo "You have requested a $type room for $nights nights, checking in on $checkin. Thank you for your order! ";
?>
shell> /path/to/phpbook.php 21/05/2005 7 single
You have requested a single room for 7 nights, checking in on 21/05/2005. Thank you for your order!
PEAR类向PHP增加更加复杂的命令行参数。
使用CLI参数
表格B
参数 | 说明 |
-a | 交互式运行Run interactively |
-c | path 从path读取php的.ini文件 |
-n | 不用读取php的.ini文件就直接运行 |
-m | 列出经过编译的模块 |
-i | 显示有关PHP构建的信息 |
-l | 检查PHP脚本的句法 |
-s | 以彩色方式显示源代码 |
-w | 显示去掉注释之后的源代码 |
-h | 显示帮助 |
交互模式
shell> /path/to/php -a
shell> /path/to/php -a
Interactive mode enabled
<?php
echo mktime();
1121187283
echo 2+2;
4
exit();
shell>
shell> /path/to/php
<?php
echo date("d-M-Y h:i:s", time());
?>
<Ctrl-D>
12-Jul-2005 06:54:04