PHP Basic CLI Pattern development does not require a detailed description of any kind of Web server

Source: Internet
Author: User
Tags cli interpreter echo command php cli
Reprint please indicate source: PHP Base: 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 that the CLI can be run on various occasions.
There are two ways to run PHP CLI scripts.

The first method is to use Php-f/path/to/yourfile.php. Invoke the PHP CLI interpreter and pass parameters to the script. This method first sets the path of the PHP interpreter, the Windows platform before running the CLI, you need to set a command similar to path c:\php, also lost the meaning of the first line of the CLI script, so it is not recommended to use this method.

The second method is to run Chmod+x < The script file name > (unix/linux Environment) to run, place the PHP file as executable, and then add a declaration in the first line of the CLI script header (similar to #! /usr/bin/php or PHP CLI interpreter location), and then execute directly on the command line. This is the preferred method of the CLI and is recommended for use.

Let's look at how to write a php cli script.

1. Writing the first CLI script
Start by creating a PHP script named myfile.php that runs the PHP CLI. The script is simple and only shows "Hello PHP cli!". The script code is as follows:

On the #!/usr/local/bin/php–q <?php//windows platform, the upstream should be: #! C:\php\php.exe-qecho "Hello php cli!";? > Do not forget to set the file to the executable permission: $ chmod 755 myfile.php then enter the following command directly, press ENTER to run: $./myfile.php If you want to run the script under Windows system, you do not need to set the 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!

Again: If on the Windows platform, The first line of the CLI script must be written in the correct php.exe location, like this (in addition, if you want to add comments to the CLI script, write the comment in the PHP tag, because the CLI interpretation only knows the first line, not the PHP tag is considered a syntax error):

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

This way, you can see that the information on the command line has been printed to prove that the CLI script has run successfully.

2. Reading parameters from the command line

If you want to get parameters from the command line, the CLI can get the number and value of the arguments from $_server[' argc ' and $_server[' argv ']. Let's create a file with the name testargs.php and the script code as follows:

#! C:\php\php.exe–q <?php//unix and Linux platforms should get parameters for #!/usr/local/bin/php–qecho "test: \ n"; echo $_server["ARGC"]. " \//Displays the parameter values passed in, starting at index 1 to show echo $_server["argv"][1]. " \ n "; echo $_server["argv"][2]. " \ n "; Echo $_server[" argv "][3]." \ n "; echo $_server["argv"][4]. " \ n ";? > enter the following code on the command line: c:\users\john>testargs.php always to be the best test get parameters: 4AlwaysToBeBest

Because we entered a string of words, the script parameters are separated by a space. As a result, PHP counts it as 4 parameters, as described below.

$_server[the "ARGC"] array returns the number of an integral type, representing a total of several parameters entered after the carriage return from the command line.

As the result of the above example shows, to access the parameter values that have been passed in, you need to start at index 1. Because the script itself's file already occupies index 0, that is $_server["argv"][0].

3. Handling I/O channels

PHP was originally designed not to be used in conjunction with the user's direct keyboard input or text output. Understanding this design is critical, because if you need to perform any action on the command line, you must be able to communicate back and forth with the user.

Input/output (I/O) channel The idea comes from a UNIX system, which provides 3 file handles for sending and receiving 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 the PHP 5 CLI, there is a file flow handle that can use 3 system constants, stdin, stdout, and stderr, respectively. Here we introduce separately.

(1) STDIN

The stdin is all called standard in or standardized input, which can obtain any data from the terminal.

Format: stdin (' Php://stdin ')

The following example shows user input:

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

This code works very much like a cat command, and turns all of its inputs into a rotation. However, it cannot receive parameters at this time.

STDIN is a standard input device for PHP, using it, the CLI php script can do more things. As in the following example:

#!/usr/local/bin/php-q the first line under the <?php//unix platform should be #!/usr/bin/php–q/* if STDIN is undefined, a new STDIN input stream is defined */if (!defined ("STDIN") {Define ("STDIN", fopen (' Php://stdin ', ' R ')} echo "Hello! What's your name (please enter): \ n"; $strName = Fread (STDIN, 100); Read in 80 characters from a new line echo ' welcome you '. $strName. " \ n ";? > After the script executes, it will display: Hello! What's your name (please enter): For example, after entering Raymond, it will be displayed: welcome you Raymond

(2) STDOUT

The STDOUT is all called standard out or standardized output, which can be output directly to the screen (or output to other programs, using stdin), if the print or ECHO statement is used in PHP CLI mode, The data is sent to the 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 (' php://stdout ', ' W '); Fwrite ($STDOUT, "Hello World"); Fclose ($STDOUT);? >

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

#!/usr/local/bin/php–qoutput #1. <?phpecho "Output #2."; Print "Output #3."?> This will get: output #1. Output #2. Output #3.

Description: A new line outside the PHP tag has been output, but the echo command or the Print command does not indicate a line break. In fact, the command prompt re-appears in the output #2. Output #3. In the same row. Any other print function that PHP has will work as normal as this function, and any function that writes back to the file is the same.

#!/usr/local/bin/php-q <?php$stdout = fopen ("Php://stdout", "W"), Fwrite ($STDOUT, "Output #1."); Fclose ($STDOUT);? >

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

(3) STDERR

STDERR is all called standard error, which is sent directly to the user terminal by default, and a "Stdin.stderr" is generated when using the stdin file handle from another application that does not read the data.

Format: stderr (' Php://stderr ')

The following script shows how to output a line of text to the error stream.

#!/usr/local/bin/php–q<?php $STDERR = fopen (' Php://stderr ', ' W '); Fwrite ($STDERR, "There is an Error"); Fclose ($STDERR);? >

PHP 5.2 can use STDOUT directly as a constant, instead of defining the variable $stdout used above, we still use custom variables for compatibility with previous versions, and if you are using PHP 5.2, you can refer to the second example of stdin.

4. Running the CLI in the background

If you are running a process and the process does not end when you exit the account, that is, running in the background or background of the system, you can use the Nohup command. The command can continue to run the appropriate process after exiting the account.

Nohup in English is the meaning of not hanging (no hang up). The general form of the command is:

Nohup–f scriptname.php &

By using the Nohup command to submit a job, all output of the job is redirected to a file named Nohup.out by default, unless the output file is specified separately.

Nohup scriptname.php > Log.txt &

In this way, the results of the PHP CLI script execution are output to log.txt, and we can use the tail command to view the content:

Tail-n50-f Log.txt

Now to implement two examples, the first one is to automatically generate a static HTML file every 10 minutes, and continue to execute. The script code is as follows:

#! /usr/local/bin/php <?phpset_time_limit (0); while (true) {@fopen ("/usr/local/www/data-dist/content/article_". Time (). ". HTML "," W "); Sleep (600);}? >

Save and exit the VI editor and give the genhtml.php file executable permissions:

#>chmod 755 genhtml.php Then let the script execute in the background, execute the following command: $nohup genhtml.php–f & Execute the above command, the following prompt appears: [1] 16623

The shell prompt appears after you press ENTER. The above hint means that all command execution output information will be placed in the Nohup.out file.

After executing the above command, the specified HTML file, such as article_111990120.html, is generated every 10 minutes in the specified directory.

How do I terminate a CLI program's background run?

You can use the KILL command to terminate the process, before terminating the process to know the PID number of the process, the process ID, we use the PS command:

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 t TYV1 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 has seen that the process ID of PHP is: 16623, then execute the KILL command: $ kill-9 16623 [1]+ Kil LED nohup/usr/local/www/data/genhtml.php

At this point the process of the command has been terminated, and then using the PS command: $ ps PID TT STAT time command 82374 P3 Ss 0:00.17-bash (bash) 82535 P3 r+ 0:00.00 PS

Just now the PHP CLI script is gone, if the direct run PS command cannot see the process, then use PS & apos two commands to view.

Note: The above example must be run on UNIX or Linux systems, such as FreeBSD, Redhat Linux, etc., the nohup command is not supported in Windows environments.

The above is the PHP Basic CLI mode development does not require any kind of Web server detailed description of content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.