Home > php教程 > php手册 > body text

命令行下执行带参数的php脚本

WBOY
Release: 2016-06-06 19:55:34
Original
1666 people have browsed it

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入 在命令行下执行带参数的php脚本的方法: php本身就是一种脚本语言,不过我们一般都是通过apache来执行php,当然php也是可以通过命令行来执行的.和perl等语言类似. 主要还是用到了php.exe这个可执行文件,

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入

    在命令行下执行带参数的php脚本的方法:

    php本身就是一种脚本语言,不过我们一般都是通过apache来执行php,当然php也是可以通过命令行来执行的.和perl等语言类似.

    主要还是用到了php.exe这个可执行文件,所以需要设置环境变量.

    看下面这个最简单的代码,phphello.php :

   

    echo “Hello php!”;

    ?>

    现在,试着在命令行提示符下运行这个程序,方法是调用CLI可执行文件并提供脚本的文件名:

    #php phphello.php

    输出Hello php!

    使用标准的输入和输出

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

   

    // ask for input

    fwrite(STDOUT, “Enter your name: ”);

    // get input

    $name = trim(fgets(STDIN));

    // write input back

    fwrite(STDOUT, “Hello, $name!”);

    ?>

    shell> php hello.php

    Enter your name: Joe

    Hello, Joe!

    在这个脚本里,fwrite()函数首先会向标准的输出设备写一条消息,询问用户的姓名.然后它会把从标准输入设备获得的用户输入信息读取到一个PHP变量里,并它把合并成为一个字符串.然后就用fwrite()把这个字符串打印输出到标准的输出设备上.

    使用命令行自变量

    在命令行里输入程序参数来更改其运行方式是很常见的做法.你也可以对CLI程序这样做.PHP CLI带有两个特殊的变量,专门用来达到这个目的:一个是$argv变量,它通过命令行把传递给PHP脚本的参数保存为单独的数组元素;另一个是$argc变量,它用来保存$argv数组里元素的个数.

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

   

    print_r($argv);

    ?>

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

    shell> php phptest.php chocolate 276 “killer tie, dude!”

    Array

    ( [0] => test.php

    [1] => chocolate

    [2] => 276

    [3] => killer tie, dude!

    )

    正如你可以从输出的结果看到的,传递给test.php的值会自动地作为数组元素出现在$argv里.要注意的是,$argvis的第一个自变量总是脚本自己的名称.

    下面是一个更加复杂的例子:

    代码

   

    // check for all required arguments

    // first argument is always name of script!

    if ($argc != 4) {

    die(“Usage: book.php ”);

    }

    // remove first argument

    array_shift($argv);

    // get and use remaining arguments

    $checkin = $argv[0];

    $nights = $argv[1];

    $type = $argv[2];

    echo “You have requested a $type room for $nights nights, checking in on $checkin. Thank you for your order! ”;

    ?>

    下面是其用法的示例:

    shell> php phpbook.php 21/05/2005 7 single

    You have requested a single room for 7 nights, checking in on 21/05/2005. Thank you for your order!

    在这里,脚本首先会检查$argc,以确保自变量的数量符合要求.它然后会从$argv里提取出每一个自变量,把它们打印输出到标准的输出

命令行下执行带参数的php脚本

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!