-
Step 1
Being able to prompt the user in a command line interface(CLI) using PHP is a very useful tool and I have enjoyed using it in my own programming tasks. Open up your script editor and your command line interface and get ready to try it for yourself!
-
Step 2
I will give you an example of my short code example. In this example, I am using fwrite and STDOUT to output a string to the command line interface. Here is the first line of code.
fwrite(STDOUT, "Hello...\nWhat is your name? "); -
Step 3
Now it is time for the user to input something into the CLI. The code for this will be using fgets and STDIN to recieve the input data. I am also using the trim function to get rid of any excess whitespace around the input data, just in case. I have set a variable, "$name", to represent the input data, so that I can call on this variable when I need it. Our code now looks like this.
fwrite(STDOUT, "Hello...\nWhat is your name? ");
$name = trim(fgets(STDIN)); -
Step 4
Entire PHP ScriptThe last step of the code is using the data that we will input! This is a simple example so all we are going to do is have the program say something back using the name that we will enter into the CLI. The final line of code will again be using fwrite and STDOUT to output a string to the CLI, but this time, that string will contain our "$name" variable. The final code looks like this. I also included an image of the code in my script editor.
fwrite(STDOUT, "Hello...\nWhat is your name? ");
$name = trim(fgets(STDIN));
fwrite(STDOUT, "Hello, $name!\n"); -
Step 5
Now we will run the code, and the following will take place... The program will output,
"Hello..."
"What is your name?"
This is the part where you input your data, or name in this case. I will enter the name Bob, and press enter to continue the script. Our variable "$name" is now equal to our input data, "Bob". The program will now output a response.
"Hello, Bob!" -
Step 6
Output of Command Line InterfaceI hope that this helps you in your own script writing. I have found prompting the user to be a very helpful and convenient. I will add an image to this step of the entire output of the program in my command line interface. Enjoy!













