This article analyzes the method of executing a php script with parameters based on the command line and obtaining the parameters. Share it with everyone for your reference, the details are as follows:
1. Why do we run php scripts on the command line?
Personally understood, there are two main reasons:
1. Using crontab to run PHP can decompress the server. Of course, there is a condition here, that is, the real-time requirements are not high. For example: the real-time requirements for friend updates in SNS are not high, but the amount of data is relatively large. If run regularly at this time, it will put a lot of pressure on the web server and database server.
2. We need to complete something on a regular basis, for example: I want to delete a user’s message a month ago. At this time, the written php script is executed in crontab, and it only needs to be run once a day. Instead of manually executing the php program.
2. Execute php with parameters under the command line and obtain the parameters.
One thing is very important. That is to execute php under the command line. There is no such thing as apache. There is no http protocol. All get and post are transmitted. The parameters have no effect at all, and an error will be reported, as follows:
zhangying@ubuntu:~$ php test.php?aaa=bbb Could not open input file: test.php?aaa=bbb
Under normal circumstances, there is no need to pass parameters to the php script that runs regularly, but sometimes, it is necessary.
1. The test.php test file is very simple, right
<?php print_r($argv); echo "\n"; echo $argc; echo "\n"; ?>
2. Calling
zhangying@ubuntu:~$ php test.php aaa ccc bbbb Array ( [0] => test.php //参数0,文件本身 [1] => aaa //参数1 [2] => ccc //参数2 [3] => bbbb //参数3 ) 4 //$argc的值,参数的总数
from the command line, this way of passing parameters, the root shell script is really like
Copy the code The code is as follows:
zhangying@ubuntu:~$ sh c1.sh aaa bbb
Readers who are interested in more PHP-related content can check out the special topics of this site: "Introduction Tutorial on PHP Basic Syntax" and "Introduction Tutorial on PHP Object-Oriented Programming"
I hope this article will be helpful to everyone in PHP programming.
The above introduces the method of executing a PHP script with parameters based on the command line and obtaining the parameters, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.