将PHP作为Shell脚本语言使用

http://tech.ddvip.com   2007年08月29日    社区交流

内容摘要:要使用PHP作为Shell脚本语言,你必须将PHP作为二进制的CGI编译,而不是Apache模式;编译成为二进制CGI模式运行的PHP有一些安全性的问题,关于解决的方法可以参见PHP手册(http://www.php.net)。

  现在我们可以使用函数“read”将我们前面编写的程序1修改一下,使他更加具有“交互性”了:

#!/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("
Hello, $first_name $last_name! Nice to meet you!
");
  ?>

  将上面的程序保存下来,运行一下,你可能会看到一件预料之外的事情:最后一行的输入变成了三行!这是因为“read”函数返回的信息还包括了用户每一行的结尾换行符“ ”,保留到了姓和名中,要去掉结尾的换行符,需要把“read”函数修改一下:

  function read() {
  $fp = fopen('/dev/stdin', 'r');
  $input = fgets($fp, 255);
  fclose($fp);
  $input = chop($input); // 去除尾部空白
  return $input;
  }
  ?>

  三、在其他语言编写的Shell脚本中包含PHP编写的Shell脚本:

  有时候我们可能需要在其他语言编写的Shell脚本中包含PHP编写的Shell脚本。其实非常简单,下面是一个简单的例子:

#!/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
");
  ?>
  EOF

  其实就是调用PHP来解析下面的代码,然后输出;那么,再试试下面的代码:

#!/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
");
  ?>
  EOF

  可以看出两次的代码唯一的不同就是第二次使用了一个变量“$myVar”,试试运行,PHP竟然给出出错的信息:“Parse error: parse error in - on line 2”!这是因为Bash中的变量也是“$myVar”,而Bash解析器先将变量给替换掉了,要想解决这个问题,你需要在每个PHP的变量前面加上“”转义符,那么刚才的代码修改如下:

#!/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
");
  ?>
  EOF

  好了,现在你可以用PHP编写你自己的Shell脚本了,希望你一切顺利。

责编:豆豆技术应用

正在加载评论...