正如我们大多数人所知,
PHP 是当今
开发动态网页的最佳语言。但很多人没有意识到用它来做 Shell 脚本也是非常不错的。PHP 作为 Shell 脚本的时候不会像 Bash 或是 Perl 那样在这方面是强项。但如果你像我一样懂 PHP 比 Perl 多一些,那么也将会有一些明显的优势。
使用 PHP 作为 Shell 语言的条件是你必须编译其为二进制的 CGI,而非 Apache 模块。这样做肯定会有一些安全问题,所以请先查阅 PHP 手册。
使用 PHP 作为 Shell 脚本与用其写动态网页在
代码上的一点不同,就是你必须要像其他 Shell 一样,先在顶部写这样一段代码:
我们使用 '-q' 是为了屏蔽 PHP 发送的 HTTP 头。当然,你仍需要在脚本的头部和底部使用标准的 PHP 标签:
现在让我们从经典的 Hello World 例子开始深入研究吧:
- #!/usr/local/bin/php -q
-
- print("Hello World!\n");
- ?>
如大家所知,我们在屏幕上简单的输出:Hello World!
·向脚本传递参数
通常你可能需要向一个脚本传递参数,在 PHP 中用一个内建的 '$argv' 数组将会很容易实现,如下例如示:
- #!/usr/local/bin/php -q
-
- $first_name = $argv[1];
- $last_name = $argv[2];
- print("Hello, $first_name $last_name! How are you today?\n");
- ?>
在上面的脚本中,我们传递两个将被显示的参数:
[yc@local yc]$scriptname.php Yeto Chiang
输出:
Hello, Yeto Chiang! How are you today?
[yc@local yc]$
在使用 PHP 作为 Shell 脚本与做动态网页之间 '$argv' 数组有一个主要的不同点。用作 Shell 脚本时,'$argv[0]' 就是你的脚本名。而做动态网页时,它就是你
查询语句的第一个参数。
·让脚本有更强的交互性
我们怎样得到用户的输入呢?我们怎样创建一个真正交互的脚本呢?PHP 本身并没有一个可以读取 Shell 命令的
函数,但是我们可以用下面的函数模拟一个:
*注:本函数仅适用于类 Unix
系统-
- function read() {
- $fp=fopen("/dev/stdin", "r");//译注:些处推荐用php://stdin,下同。
- $input=fgets($fp, 255);
- fclose($fp);
- return $input;
- }
- ?>
这个函数打开一个标准输入
文件的指针 (/dev/stdin on *nix),我们可以用该指针读取任意东西,直到大小达到 255 个字节、新行或是 EOF。这种情况下,最容易因为新行停止读取,然后它会关闭指针并返回
数据。
现在我们修改前面的脚本,让其使用刚刚创建的 'read' 函数来等待用户输入:
- #!/usr/local/bin/php -q
-
- function read() {
- $fp=fopen("/dev/stdin", "r");
- $input=fgets($fp, 255);
- fclose($fp);
- return $input;
- }
- print("What is your first name? ");
- $first_name = read();
- print("What is your last name? ");
- $last_name = read();
- print("\nHello, $first_name $last_name! Nice to meet you!\n");
- ?>
你可能发现了,当我们执行这个脚本的时候,本应显示成一行的最后一行被分割成三行。这是因为我的们的 'read' 函数同样也读取了新行。这一点很容易修正,只要在返回数据之前去掉新行就行了:
-
- function read() {
- $fp=fopen("/dev/stdin", "r");
- $input=fgets($fp, 255);
- fclose($fp);
- return str_replace("\n", "", $input);
- }
- ?>
·将 PHP Shell 脚本嵌入正规的 Shell 脚本
有的时候可能需要将 PHP Shell 嵌入到一段已经写好的 Bash 或是其他 Shell 中,这相当容易,但也要小心些。
首先是如何嵌入 PHP 代码:
- #!/bin/bash
- echo This is the Bash section of the code.
- /usr/local/bin/php -q << EOF
-
- print("This is the PHP section of the code\n");
- ?>
- EOF
非常简单吧?当你添加一个变量的时候就要小心了,看下面这个代码片断:
- #!/bin/bash
- echo This is the Bash section of the code.
- /usr/local/bin/php -q << EOF
-
- $myVar = "PHP";
- print("This is the $myVar section of the code.\n");
- ?>
- EOF
你将会得到一个错误:
Parse error: parse error in - on line 2
要修正这个错误,你需要转义代码中所有的 '$' 字符:
- #!/bin/bash
- echo This is the Bash section of the code.
- /usr/local/bin/php -q << EOF
-
- \$myVar = "PHP";
- print("This is the \$myVar section of the code.\n");
- ?>
- EOF
现在你可以用 PHP 开始创建自己的 Shell 脚本了。
原文地址:
译者:姜运涛
阅读(121) | 评论(0) | 转发(0) |