How to pass parameters to php under shell command

伊谢尔伦
Release: 2023-03-11 14:32:01
Original
2747 people have browsed it

Usually PHP makes HTTP requests, and you can use GET or POST to receive parameters. Sometimes you need to execute PHP as a script under a shell command, such as a scheduled task. This involves the issue of how to pass parameters to php under the shell command. There are usually three ways to pass parameters.

1. Use $argv or $argc parameter to receive

<?php
/**
 * 使用 $argc $argv 接受参数
 */
 echo "接收到{$argc}个参数";
print_r($argv);
Copy after login

Execute

[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]#
Copy after login

2. Use getopt Function

<?php
/**
 * 使用 getopt函数
 */
 
$param_arr = getopt(&#39;a:b:&#39;);
print_r($param_arr);
Copy after login

Execution

[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
)
Copy after login

3. Prompt the user to input

<?php
/**
 * 提示用户输入,类似Python
 */
fwrite(STDOUT,&#39;请输入您的博客名:&#39;);
echo &#39;您输入的信息是:&#39;.fgets(STDIN);
Copy after login

Execution

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

Please enter your blog name:
The information you entered is:
You can also do this, preventing users from entering empty information

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

Execute

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


The above is the detailed content of How to pass parameters to php under shell command. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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 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!