Home > Article > Backend Development > How to execute a php script with parameters based on the command line and obtain the parameters, php script_PHP tutorial
This article analyzes the method of executing a php script with parameters based on the command line and obtain 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, 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 a certain thing regularly. For example: I want to delete the user's message a month ago. At this time, the written php script is executed in the crontab, and it only needs to be run once a day. Instead of manually executing the php program.
2. Execute php with parameters from the command line and obtain the parameters
One thing is very important, is to execute php from the command line without using apache and other such things. There is no http protocol, and all get and post parameters will not work at all, and will also Report an error , 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. test.php test file, very simple
<?php print_r($argv); echo "\n"; echo $argc; echo "\n"; ?>
2. Call from command line
zhangying@ubuntu:~$ php test.php aaa ccc bbbb Array ( [0] => test.php //参数0,文件本身 [1] => aaa //参数1 [2] => ccc //参数2 [3] => bbbb //参数3 ) 4 //$argc的值,参数的总数
This method of passing parameters is really similar to the root shell script
Copy code The code is as follows: zhangying@ubuntu:~$ sh c1.sh aaa bbb
I passed two parameters aaa bbb to c1.sh, and the shell will get three parameters. $0 is the file itself, $1 is parameter 1, and $2 is parameter 2. The difference is that php gets it in the form of an array, but the shell does not.
Readers who are interested in more PHP-related content can check out the special topics on 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.