`

php 命令行

    博客分类:
  • PHP
阅读更多
PHP 使用cli可以参考官网:http://cn.php.net/manual/en/features.commandline.php
1.php cli 运行有两种方式
eg:
方式一:test1.php
<?php
echo 'test'."\n";

可以使用php test1.php方式运行
方式二:test2.php
#!/usr/bin/php -q
<?php
echo 'test'."\n";

将test2.php具有可执行权限 ./test2.php运行(类似shell处理,文件名可以随意)

2.判断PHP cli模式的方式有一下几种
php_sapi_name() === 'cli'

3.php options 常用
-a 交互是运行
-d 运行脚本设置当前环境变量
-i 显示phpinfo()信息
-m 列出安装module
-r 运行脚本
-R 对于文件中的每一行都运行代码
-F 对于文件中的每一行都执行指定的文件

3.输入输出处理
<?php
$stdin = fopen('php://stdin', 'r');
or
$line = trim(fgets(STDIN)); // reads one line from STDIN
fscanf(STDIN, "%d\n", $number); // reads number from STDIN
?>

<?php
$stdout = fopen('php://stdout', 'w');
or
fwrite(STDOUT, $stdout);
?>

<?php
$stderr = fopen('php://stderr', 'w');
or
fwrite(STDERR, 'error');
?>

usage:处理命令行输入
print "Type message. Type '.' on a line by itself\n";
$fp = fopen('php://stdin', 'r') or die($php_errormsg);
$lastLine = false;
$msg = '';
while (!$lastLine) {
    $nextLine = fgets($fp, 1024);
    if(".\n" == $nextLine) {
        $lastLine = true; 
    } else {
        $msg .= $nextLine; 
    }
}
fclose($fp);
print "\nMessage:\n$msg";


在此还可以是使用readline: http://cn.php.net/manual/en/book.readline.php

3.$argc & $argv 是全局变量(register_argc_argv该设置默认打开)
有一个有用函数格式化参数:
<?php
/**
 * get php cli arguments
 * Usage: php test.php --foo --bar=baz
		  php test.php --foo -b=baz
		  php test.php -abc
		  php test.php arg1 arg2 arg3
 */
function arguments($argv) {
    array_shift($argv);
    $out = array();
	if($argv) {
		foreach ($argv as $arg) {
			if (substr($arg,0,2) == '--') {
				$eqPos = strpos($arg,'=');
				if ($eqPos === false){
					$key = substr($arg,2);
					$out[$key] = isset($out[$key]) ? $out[$key] : true;
				} else {
					$key = substr($arg,2,$eqPos-2);
					$out[$key] = substr($arg,$eqPos+1);
				}
			} else if (substr($arg,0,1) == '-') {
				if (substr($arg,2,1) == '=') {
					$key = substr($arg,1,1);
					$out[$key] = substr($arg,3);
				} else {
					$chars = str_split(substr($arg,1));
					foreach ($chars as $char) {
						$key = $char;
						$out[$key] = isset($out[$key]) ? $out[$key] : true;
					}
				}
			} else {
				$out[] = $arg;
			}
		}
	}
    return $out;
}


4.处理类似密码屏蔽显示
<?php
print 'Login:';
$fp = fopen('php://stdin', 'r');
$username = trim(fgets($fp, 64));
print 'Password:';
`/bin/stty -echo`;
$password = trim(fgets($fp, 64)) or die($php_errormsg);
`/bin/stty echo`;
print "\n";


 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics