Home >Backend Development >PHP Tutorial >Introduction to php-cli (use Shell if you don't know Shell language)_PHP Tutorial
1. Basic knowledge
1.1 What is Shell programming?
In Unix, the shell is not a simple command interpreter (typically DOS in Windows), but a Full-featured programming environment. Shell is a part of the operating system used to deal with users and can be used to coordinate various commands [1]. Shell programming can flexibly solve a large number of repetitive tasks, which is very convenient. However, the syntax of Shell is very weird (personal opinion) and not easy to remember. It would be great if the language you are familiar with now can be used to write shell - such as php - so that you can quickly develop Shell programs (such as the background of my Preminder Program), so this article was created. This article uses Linux as an example to illustrate the usage of php-cli. The versions on other platforms are similar.
1.2 What is php-cli?
As mentioned just now, we can use php to develop Shell programs. Some students may ask: "Isn't PHP used to make web pages? -_-". Yes, php can be used to make dynamic web pages, and php was originally developed as a language for making dynamic web pages, but in theory php can be used to make any program, even desktop programs, and php-cli is php on the command line. The running support environment is what we call the environment support that can be used to write Shell.
php-cli is the abbreviation of php Command Line Interface. As its name implies, it is the interface for php to run on the command line, which is different from the php environment running on the web server (php-cgi, isapi, etc.) 【2】.
In other words, PHP can not only write front-end web pages, it can also be used to write back-end programs.
2. Execute the php-cli script
2.1 The syntax of php-cli
Of course it is exactly the same as php, because it is php! However, some default parameters are different from php-cgi, such as running time: the default running time of php-cli is infinite, while the default setting of web php is 30s.
2.2 Execute php-cli script
2.2.1. Execute php directly in the terminal
kangzj@localhost# php -r 'print_r(get_defined_constants());'2.2.2. Run the php-cli script file
kangzj@localhost# php my_script.php
kangzj@localhost# php -f my_script.php The php file mentioned above is no different from ordinary php files. Another way is to instruct the interpreter in a file, and you can execute the script directly in the terminal with "./test.php". test.php looks like the following: