免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3089 | 回复: 1
打印 上一主题 下一主题

如何在命令行下运行PHP脚本[带参数] [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-11-07 16:07 |只看该作者 |倒序浏览
如何在命令行下运行PHP脚本[带参数]





创建一个简单的文本文件,其中包含有以下PHP代码,并把它保存为hello.php:
<?php
echo "Hello from the CLI";
?>
现在,试着在命令行提示符下运行这个程序,方法是调用CLI可执行文件并提供脚本的文件名:
#php phphello.php
输出Hello from the CLI


-----------------使用标准的输入和输出
你可以在自己的PHP脚本里使用这三个常量,以接受用户的输入,或者显示处理和计算的结果。要更好地理解这一点,可以看看下面的脚本(

列表A):

列表A
  1. <?php
  2. // ask for input
  3. fwrite(STDOUT, "Enter your name: ");

  4. // get input
  5. $name = trim(fgets(STDIN));

  6. // write input back
  7. fwrite(STDOUT, "Hello, $name!");
  8. ?>
  9. Look what happens when you run it:
  10. shell> php hello.php
  11. Enter your name: Joe
  12. Hello, Joe!
复制代码
在这个脚本里,fwrite()函数首先会向标准的输出设备写一条消息,询问用户的姓名。然后它会把从标准输入设备获得的用户输入信息读

取到一个PHP变量里,并它把合并成为一个字符串。然后就用fwrite()把这个字符串打印输出到标准的输出设备上。


-----------------使用命令行自变量
  在命令行里输入程序参数来更改其运行方式是很常见的做法。你也可以对CLI程序这样做。PHP CLI带有两个特殊的变量,专门用来达到这个

目的:一个是$argv变量,它通过命令行把传递给PHP脚本的参数保存为单独的数组元素;另一个是$argc变量,它用来保存$argv数组里元素的

个数。

    用PHP脚本编写一段读取$argv并处理它所含参数的代码是很简单的。试试列表B里的示例脚本,看看它是如何工作的:

列表B
  1. <?php
  2. print_r($argv);
  3. ?>

  4. Run this script by passing it some arbitrary values, and check the output:

  5. shell> php phptest.php chocolate 276 "killer tie, dude!"
  6. Array
  7. ( [0] => test.php
  8. [1] => chocolate
  9. [2] => 276
  10. [3] => killer tie, dude!
  11. )
复制代码
正如你可以从输出的结果看到的,传递给test.php的值会自动地作为数组元素出现在$argv里。要注意的是,$argvis的第一个自变量总是

脚本自己的名称。


下面是一个更加复杂的例子(列表C):

列表C



代码
  1. <!--<br/ /><br/ />Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />http://www.CodeHighlighter.com/<br/ /><br/ />--><?php
  2. // check for all required arguments
  3. // first argument is always name of script!
  4. if ($argc != 4) {
  5. die("Usage: book.php <check-in-date> <num-nights> <room-type> ");
  6. }

  7. // remove first argument
  8. array_shift($argv);

  9. // get and use remaining arguments
  10. $checkin = $argv[0];
  11. $nights = $argv[1];
  12. $type = $argv[2];
  13. echo "You have requested a $type room for $nights nights, checking in on $checkin. Thank you for your order! ";
  14. ?>
复制代码
下面是其用法的示例:
  1. shell> php phpbook.php 21/05/2005 7 single
  2. You have requested a single room for 7 nights, checking in on 21/05/2005. Thank you for your order!
复制代码
在这里,脚本首先会检查$argc,以确保自变量的数量符合要求。它然后会从$argv里提取出每一个自变量,把它们打印输出到标准的输出
  1. <script type="text/javascript"></script>
复制代码

论坛徽章:
0
2 [报告]
发表于 2011-11-07 22:28 |只看该作者
谢谢楼主
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP