- echo "Hello from the CLI";
- ?>
Copy CodeNow, try running the program at a command-line prompt by invoking the CLI executable and providing the script's file name: #php phphello.php output Hello from the CLI Using standard inputs and outputs you can use these three constants in your own PHP scripts to accept user input, or to display the results of processing and calculations. To understand this better, take a look at the following code.
Ask for input
- Fwrite (STDOUT, "Enter Your Name:");
Get input
- $name = Trim (fgets (STDIN));
Write input back
- Fwrite (STDOUT, "Hello, $name!");
- ?>
Copy CodeLook how happens when do 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 asking for 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. The string is then printed out to the standard output device using fwrite (). #---It is common practice to use command-line arguments to enter program parameters on the command line to change how they are run. You can also do this to the CLI program. The PHP CLI has two special variables for this purpose: one is the $ARGV variable, which saves the arguments passed to the PHP script as a separate array element through the command line, and the other is the $ARGC variable, which is used to hold the number of elements in the $ARGV array. It is very simple to write a piece of code that reads $ARGV and processes the parameters contained in a PHP script. Test the following sample script to see how it works:
- Print_r ($ARGV);
- ?>
Copy CodeRun 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 the test.php is automatically shown as an array element in the $ARGV. Note that the first argument $argvis is always the script's own name. 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 the $nights nights, checking in on $checkin. Thank for your order! ";
- ?>
Copy CodeThe following is an example of its usage:shell> PHP phpbook.php 21/05/2005 7 Singleyou has requested a single hostel for 7 nights, checking in on 21/05 /2005. Thank for your order! Here, the script first checks the $ARGC to ensure that the number of independent variables meets the requirements. It then extracts each of the arguments from the $argv and prints them out to the standard output. |