Home  >  Article  >  Backend Development  >  PHP basics CLI mode development does not require a detailed introduction to any kind of web server

PHP basics CLI mode development does not require a detailed introduction to any kind of web server

黄舟
黄舟Original
2017-03-06 09:41:331685browse

Please indicate the source for reprinting: PHP basics: CLI mode development does not require any kind of web server

PHP CLI mode development does not require any kind of web server (including Apache or MS IIS, etc.), so the CLI can run in various situations.
There are two ways to run PHP CLI scripts.

The first method is to use php -f /path/to/yourfile.php. Call the PHP CLI interpreter and pass parameters to the script. This method first requires setting the path of the php interpreter. Before running the CLI on the Windows platform, you need to set a command similar to path c:\php. This also loses the meaning of the first line of the CLI script, so this method is not recommended.

The second method is to first run chmod+x cef840959e3eaec2eeedcf086fe48fcc (UNIX/Linux environment), set the PHP file to executable permissions, and then add a statement in the first line of the CLI script header (similar to in #!/usr/bin/php or the PHP CLI interpreter location), and then execute it directly on the command line. This is the CLI preferred method and is recommended.

Let's take a look at how to write PHP CLI scripts.

1. Writing the first CLI script
First create a PHP script named myfile.php for running the PHP CLI. The script is simple and just displays "Hello PHP CLI!" The script code is as follows:

#!/usr/local/bin/php –q 3817aebe58485f5b0d2886a99959e6d0 No Forgot to set the executable permissions for the file: $ chmod 755 myfile.php Then enter the following command directly and press Enter to run: $ ./myfile.php If you want to run the script under Windows system, do not If you need to set file properties, you can run the script directly. Microsoft Windows [Version 6.0.6000] Copyright (C) 2006 Microsoft Corporation. all rights reserved. C:\ >myfile.php Hello PHP CLI!

Let me reiterate: If you are on Windows platform, the first line of the CLI script must write the correct location of php.exe, like this (in addition, if you want to add a comment statement to the CLI script, you must write the comment in the PHP tag , because the CLI interpretation only recognizes the first line, and it is not considered a syntax error in the PHP tag):

#!C:\php\php.exe -q

In this way, you can see that the information has been printed on the command line, proving that the CLI script has been successfully run.

2. Read parameters from the command line

If you want to get parameters from the command line, the CLI can get the number and value of parameters from $_SERVER['argc'] and $_SERVER['argv'']. Let’s create another file named testargs.php. The script code is as follows:

#!C:\php\php.exe –q 9a9cda8483f14fb3feaa0e5f308b9519Enter the following on the command line Code: C:\Users\John>testargs.php Always To Be Best test gets parameters: 4AlwaysToBeBest

Because we entered a string of words, "Always To Be Best", the script parameters are separated by spaces. Therefore, PHP counts it as 4 parameters, which is explained below.

The $_SERVER["argc"] array returns an integer number, representing the total number of parameters entered after pressing Enter on the command line.

As can be seen from the results of the above example, to access the parameter value that has been passed in, you need to start from index 1. Because the file of the script itself already occupies index 0, which is $_SERVER["argv"][0].

3. Handle I/O channels

PHP was not originally designed for use with direct keyboard input or text output from the user. Understanding this design is crucial because if you need to perform any action at the command line, you must be able to communicate back and forth with the user.

The idea of ​​input and output (I/O) channels comes from the UNIX system, which provides three file handles to send and receive data from an application and user terminal.

We can redirect the output of a script to a file:

php world.php > outputfile

If you are under a UNIX system, you can also use a channel to direct to another command or application. For example:

php world.php | sort.

In PHP 5 CLI, there is a file stream handle that can use 3 system constants, namely STDIN, STDOUT and STDERR. Below we introduce them separately.

(1) STDIN

STDIN stands for standard in or standard input. Standard input can obtain any data from the terminal.

Format: stdin (’php://stdin’)

The following example displays user input:

#!/usr/local/bin/php -q<?php $file = file_get_contents("php://stdin", "r");echo $file;?>

This code works much like the cat command, rotating all input provided to it. However, it cannot receive parameters at this time.

STDIN is the standard input device of PHP. Using it, CLI PHP scripts can do more things. Such as the following example:

#!/usr/local/bin/php -q 35f3fa9bb22ed6134c8d00a361cd1fb2After the script is executed, it will display: Hello !What is your name (please enter): For example, after entering Raymond, it will be displayed: Welcome Raymond

(2) STDOUT

STDOUT stands for standard out or standard output. Standard output can be output directly to the screen (it can also be output to other programs and obtained using STDIN). If you use print or echo statements in PHP CLI mode , the data will be sent to STDOUT.

Format: stdout (’php://stdout’)

We can also use PHP functions for data flow output. As in the following example:

#!/usr/local/bin/php –q<?php $STDOUT = fopen(&#39;php://stdout&#39;, &#39;w&#39;);fwrite($STDOUT,"Hello World"); fclose($STDOUT);?>

The output result is as follows: Hello World For example, the echo and print commands print to the standard output.

#!/usr/local/bin/php –qOutput #1.<?phpecho "Output #2.";print "Output #3." ?>这将得到:Output #1.Output #2.Output #3.

Explanation: New lines outside the PHP tag have been output, but there is no line break indicated in the echo command or print command. In fact, the command prompt reappears on the same line as Output #2.Output #3. Any other printing function that PHP has will work just like this function, as will any function that writes back to a file.

#!/usr/local/bin/php -q <?php$STDOUT = fopen("php://stdout", "w");
fwrite($STDOUT, "Output #1."); fclose($STDOUT);?>

The above code will explicitly open php://stdout as an output channel, and php://output usually operates in the same way as php://stdout.

(3)STDERR

STDERR全称为standard error,在默认情况下会直接发送至用户终端,当使用STDIN文件句柄从其他应用程序没有读取到数据时会生成一个“stdin.stderr”。

格式:stderr (’php://stderr’)

下面的脚本表示如何把一行文本输出到错误流中。

#!/usr/local/bin/php –q<?php $STDERR = fopen(&#39;php://stderr&#39;, &#39;w&#39;);
fwrite($STDERR,"There was an Error"); fclose($STDERR);?>

PHP 5.2可以直接使用STDOUT作为常量,而不是定义上面使用的变量$STDOUT,为了兼容之前版本,我们仍使用了自定义变量,如果您使用的是PHP 5.2,则可以参考STDIN的第二个例子。

4.后台运行CLI

如果正在运行一个进程,而且在退出账户时该进程还不会结束,即在系统后台或背景下运行,那么就可以使用nohup命令。该命令可以在退出账户之后继续运行相应的进程。

nohup在英文中就是不挂起的意思(no hang up)。该命令的一般形式为:

nohup –f scriptname.php &

使用nohup命令提交作业,在默认情况下该作业的所有输出都被重定向到一个名为nohup.out的文件中,除非另外指定了输出文件。

nohup scriptname.php > log.txt &

这样,PHP CLI脚本执行后的结果将输出到log.txt中,我们可以使用tail命令查看该内容:

tail -n50 -f log.txt

现在再来实现两个例子,第一个是每隔10分钟自动生成一个静态HTML文件,并一直执行下去。脚本代码如下:

#! /usr/local/bin/php <?phpset_time_limit(0);
while(true){@fopen("/usr/local/www/data-dist/content/ article_".time().".html","w");
sleep(600);}?>

保存并且退出vi编辑器,然后赋予genHTML.php文件可执行权限:

#>chmod 755 genHTML.php 然后让脚本在后台执行,执行如下命令:$nohup genHTML.php –f &执行上述命令后出现如下提示:[1] 16623

按回车键后将出现shell提示符。上面的提示就是说,所有命令执行的输出信息都会放到nohup.out文件中。

执行上面命令后,每隔10分钟就会在指定的目录生成指定的HTML文件,如article_111990120.html等文件。

如何终止CLI程序的后台运行呢?

可以使用kill命令来终止这个进程,终止进程之前要知道进程的PID号,即进程ID,我们使用ps命令:

www# ps PID TT STAT TIME COMMAND 561 v0 Is+ 0:00.00 
/usr/libexec/getty Pc ttyv0 562 v1 Is+ 0:00.00 /usr/libexec/getty Pc ttyv1 563 v2 Is+ 0:00.00 
/usr/libexec/getty Pc ttyv2 564 v3 Is+ 0:00.00 /usr/libexec/getty Pc ttyv3 565 v4 Is+ 0:00.00 
/usr/libexec/getty Pc ttyv4 566 v5 Is+ 0:00.00 /usr/libexec/getty Pc ttyv5 567 v6 Is+ 0:00.00 
/usr/libexec/getty Pc ttyv6 568 v7 Is+ 0:00.00 /usr/libexec/getty Pc ttyv7 16180 p0 I 0:00.01 
su 16181 p0 S 0:00.06 _su (csh) 16695 p0 R+ 0:00.00 ps 16623 p0 S 0:00.06 
/usr/local/bin/php /usr/local/www/data/genHTML.php 
已经看到PHP的进程ID是:16623,
于是再执行kill命令:$ kill -9 16623 [1]+ Killed nohup /usr/local/www/data/genHTML.php

这时该命令的进程就已经被终止了,再使用ps命令:$ ps PID TT STAT TIME COMMAND 82374 p3 Ss 0:00.17 -bash (bash) 82535 p3 R+ 0:00.00 ps

刚才的PHP CLI脚本已经没有了,如果直接运行ps命令无法看到进程,那么就结合使用ps & apos两个命令来查看。

注意:上面例子必须运行在UNIX或者Linux系统中,如FreeBSD、Redhat Linux等,在Windows环境不支持nohup命令。

   

以上就是PHP基础  CLI模式开发不需要任何一种Web服务器的详细介绍的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement:
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