`

php shell脚本

 
阅读更多

、编写一个具有交互式的Shell脚本: 

  如果一个Shell脚本仅仅是自己运行,失去了交互性,那么也没有什么意思了。当PHP用于Shell脚本的编写的时候,怎么读取用户输入的信息呢?很不幸的是PHP自身没有读取用户输入信息的函数或者方法,但是我们可以效仿其他语言编写一个读取用户输入信息的函数“read”: 

  <?php 
  function read() { 
  $fp = fopen('/dev/stdin', 'r'); 
  $input = fgets($fp, 255); 
  fclose($fp); 
  return $input; 
  } 
  ?>


  需要注意的是上面这个函数只能用于Unix系统(其他系统需要作相应的改变)。上面的函数会打开一个文件指针,然后读取一个不超过255字节的行(就是fgets的作用),然后会关闭文件指针,返回读取的信息。 

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

  #!/usr/local/bin/php -q 
  <?php 
  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”函数返回的信息还包括了用户每一行的结尾换行符“\n”,保留到了姓和名中,要去掉结尾的换行符,需要把“read”函数修改一下: 

  <?php 
  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 
  <?php 
  print("This is the PHP section of the code\n"); 
  ?> 
  EOF


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

  #!/bin/bash 
  echo This is the Bash section of the code. 

  /usr/local/bin/php -q << EOF 
  <?php
  $myVar = 'PHP'; 
  print("This is the $myVar section of the code\n"); 
  ?> 
  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 
  <?php 
  \$myVar = 'PHP'; 
  print("This is the \$myVar section of the code\n"); 
  ?>
  EOF


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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics