The grand finale

To finish this off, I want to show you something to help widen your horizons with regards to PHP CLI development: dialog. This neat little program, probably already installed on your system (if not, you will need it to continue), allows you to create basic dialogs for shell environments. Furthermore, we can call dialog direct from our PHP scripts and grab the response.

In order to demonstrate how dialog is called, some of the options that can be passed to it, and how to grab and make use of its return value using PHP, here's a big chunk o' code:

`dialog --msgbox "This demonstrates PHP interacting smoothly with dialogs." 10 40`;
$result = `dialog --menu "Please select an option" 0 0 0 "1)" "File Selection" "2)" "Calendar" "3)" "Password Box" "4)" "Checklist" 2>/dev/stdout`;

    switch (
$result) {
$result = `dialog --fselect /usr/bin 0 0 2>/dev/stdout`;
"The filename you selected was $result\n\n";
$result = `dialog --calendar "When is your birthday this year?" 0 0 22 12 2003 2>/dev/stdout`;
"The date you selected was $result\n\n";
$result = `dialog --passwordbox "Please enter your MySQL password." 0 0 2>/dev/stdout`;
"The password you entered was $result\n\n";
$result = `dialog --checklist "Please select your Foo" 0 0 0 "1)" "Some Option" "on" "2)" "Another Option" "off" 2>/dev/stdout`;
"The options you chose were $result\n\n";

As you can see from the script, dialog does most of the hard work. Note that I am using back ticks (`), not single quotes. On UK keyboards the back tick key is to the left of the 1 key and above the Tab key. If you recall, the back tick is known as the execution operator: PHP tries to execute the contents of back ticks as shell commands, returning any output.

So, in line 4, the command 'dialog --menu "Please select.........' is executed as it is contained within back ticks, and any output from it is placed into $result. $result is then put through a switch/case to decide what menu option the user chose, and then dialog is re-run with a layout dependent on what the user chose in the first dialog.

This isn't a dialog tutorial, so I am not going to go into any further depth regarding the usages above - type "man dialog" to learn more. The important thing is that you can hopefully see another way you can make good use of PHP - one could run an SQL SELECT query on a database and create a dialog with values in for the user to select, for example.

Save the script as phpcli4.php and try it yourself. Remember, you will need to have dialog accessible to try the above. Typing "dialog" by itself will bring up a list of all the parameters it can take - try amending the above example to include new functionality.


Next chapter: CLI Conclusion >>

Previous chapter: Sending code direct to PHP

Jump to:


Home: Table of Contents

Follow us on or Twitter

Username:   Password:
Create Account | About TuxRadar