- Echo "Hello from the CLI ";
- ?>
Now, try to run this program at the command line prompt by calling the CLI executable file and providing the Script File name: # php phphphello. php outputs Hello from the CLI With standard input and output, you can use these three constants in your PHP script to accept user input or display the processing and computing results. To better understand this, you can refer to the following code.
// Ask for input
- Fwrite (STDOUT, "Enter your name :");
// Get input
- $ Name = trim (fgets (STDIN ));
// Write input back
- Fwrite (STDOUT, "Hello, $ name! ");
- ?>
Look what happens when you run it: shell> php hello. phpEnter your name: JoeHello, Joe!?> In this script, the fwrite () function first writes a message to the standard output device and asks the user's name. It then reads the user input information obtained from the standard input device into a PHP variable and merges it into a string. Then, use fwrite () to print the string to the standard output device. # --- It is common to enter program parameters in the command line to change the running mode using the command line independent variables. You can also do this for the CLI program. Php cli has two special variables to achieve this purpose: one is the $ argv variable, which saves the parameters passed to the PHP script as separate array elements through the command line; the other is the $ argc variable, which is used to save the number of elements in the $ argv array. It is very easy to write a piece of code that reads $ argv and processes the parameters it contains in a PHP script. Test the following sample script to see how it works:
- Print_r ($ argv );
- ?>
Run this script by passing it some arbitrary values, and check the output: Shell> php phptest. php chocolate 276 "killer tie, dude! "Array ([0] => test. php [1] => chocolate [2] => 276 [3] => killer tie, dude !) As you can see from the output, the value passed to test. php will automatically appear in $ argv as an array element. Note that the first independent variable of $ argvis is always the name of the script. The following is a more complex example:
// Check for all required arguments
- // First argument is always name of script!
- If ($ argc! = 4 ){
- Die ("Usage: book. php ");
- }
// Remove first argument
- Array_shift ($ argv );
// Get and use remaining arguments
- $ Checkin = $ argv [0];
- $ Nights = $ argv [1];
- $ Type = $ argv [2];
- Echo "You have requested a $ type room for $ nights, checking in on $ checkin. Thank you for your order! ";
- ?>
Example: shell> php phpbook. php 21/05/2005 7 singleYou have requested a single room for 7 nights, checking in on 21/05/2005. Thank you for your order! Here, the script first checks $ argc to ensure that the number of independent variables meets the requirements. It then extracts each independent variable from $ argv and prints them to the standard output. |