Heim  >  Artikel  >  Backend-Entwicklung  >  PHP命令行脚本接收传入参数的三种方式_PHP

PHP命令行脚本接收传入参数的三种方式_PHP

WBOY
WBOYOriginal
2016-05-31 19:30:44774Durchsuche

通常PHP都做http方式请求了,可以使用GET or POST方式接收参数,有些时候需要在shell命令下把PHP当作脚本执行,比如定时任务。这就涉及到在shell命令下如何给php传参的问题,通常有三种方式传参。
一、使用$argv or $argc参数接收

代码如下:


/**
 * 使用 $argc $argv 接受参数
 */
 
echo "接收到{$argc}个参数";
print_r($argv);


执行

代码如下:


[root@DELL113 lee]# /usr/local/php/bin/php test.php
接收到1个参数Array
(
    [0] => test.php
)
[root@DELL113 lee]# /usr/local/php/bin/php test.php a b c d
接收到5个参数Array
(
    [0] => test.php
    [1] => a
    [2] => b
    [3] => c
    [4] => d
)
[root@DELL113 lee]#


二、使用getopt函数

代码如下:


/**
 * 使用 getopt函数
 */
 
$param_arr = getopt('a:b:');
print_r($param_arr);


执行

代码如下:


[root@DELL113 lee]# /usr/local/php/bin/php test.php -a 345
Array
(
    [a] => 345
)
[root@DELL113 lee]# /usr/local/php/bin/php test.php -a 345 -b 12q3
Array
(
    [a] => 345
    [b] => 12q3
)
[root@DELL113 lee]# /usr/local/php/bin/php test.php -a 345 -b 12q3 -e 3322ff
Array
(
    [a] => 345
    [b] => 12q3
)


三、提示用户输入

代码如下:


/**
 * 提示用户输入,类似Python
 */
fwrite(STDOUT,'请输入您的博客名:');
echo '您输入的信息是:'.fgets(STDIN);


执行

代码如下:


[root@DELL113 lee]# /usr/local/php/bin/php test.php


请输入您的博客名: www.bitsCN.com
您输入的信息是: www.bitsCN.com
你也可以这么干,不让用户输入空信息

代码如下:


/**
 * 提示用户输入,类似Python
 */
 
$fs = true;
 
do{
oif($fs){
fwrite(STDOUT,'请输入您的博客名:');
$fs = false;
}else{
fwrite(STDOUT,'抱歉,博客名不能为空,请重新输入您的博客名:');
}
 
$name = trim(fgets(STDIN));
 
}while(!$name);
 
echo '您输入的信息是:'.$name."\r\n";


执行

代码如下:


[root@DELL113 lee]# /usr/local/php/bin/php test.php
请输入您的博客名:
抱歉,博客名不能为空,请重新输入您的博客名:
您输入的信息是:

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn