Broad Network


Writing a PHP Command Line Tool

Foreword: In this article I explain how to write a command line tool.

By: Chrysanthus Date Published: 19 Jan 2019

Introduction

In this article I explain how to write a command line tool. When do you need a command line tool? - For applications where commands are issued, one at a time, at the console! For teaching the use of an application! For illustrative applications such as University Computer Science projects! For illustrative applications for seminars! You should have read the previous series before reaching here, as this is the continuation.

It is actually simple to write a PHP command line tool. You might have heard the word application above and maybe you cannot write an application, and you are probably thinking that since you cannot write an application, so you cannot write a command line tool. That is a mistake you are making if you are thinking like that. You are not the only one who would make such a mistake. As you will see below, it is so easy to write a command line tool, “that it will pull off your socks”.

I use the Windows Operating System and the directory, c:/Apache24/htdocs. The operations are similar with other operating systems.

The Console
At the early days of computing, screens were monochrome (black and white). Programming with such screens is command line programming. Today, you can imitate the console screen. With the Windows Operating System, use the Command Prompt window. Consult the help manual of your operating system to see how to open this window.

Directories
I prefer to work from the C:\ prompt. At the command prompt window, type

    cd c:\

and press the Enter key, and you will work from the C:\> prompt.

Type the following program in your text editor and save it with the name temp.php, in the c:/Apache24/htdocs directory (create the directory and path if necessary).

<?php

    echo 'seen';

?>

This program just echoes "seen" to the console. To run a program at the console, the syntax is:

    c:/path/to/php_interpreter c:/path/to/file.php

Type the following command and press the Enter key and you should see "seen" displayed at the console:

    c:/PHP/php c:/Apache24/htdocs/temp.php

$argv and $argc Variables
In a PHP script, the $argv variable is an inbuilt PHP array that has the arguments sent to the script from the console; when you command a PHP script file to run. The first element, $argv[0] is the name of the PHP script (program) file. The rest of the arguments are the arguments typed when the DOS command was typed (and then the Enter Key pressed).

$argc is an inbuilt integer variable that holds the number of arguments sent (to the $argv array). This number includes the first element, which is the file-name.

Type the following code and safe the file as temp.php, in the c:/Apache24/htdocs directory:

<?php

    echo $argc, "\n";

    echo "\n";

    echo $argv[0], "\n";
    echo $argv[1], "\n";
    echo $argv[2], "\n";
    echo $argv[3], "\n";

?>

Open the Command Prompt window (if it is not already open).

Type the following command with the arguments (one two three), and press Enter (key):

    c:/PHP/php c:/Apache24/htdocs/temp.php one two three

The output is:

    4

    c:/Apache24/htdocs/temp.php
    one
    two
    three

The readline() Function
The syntax is:

    string readline ([ string $prompt ] )

The function reads a single line as a string and returns the string from the user, to the program (calling function). The line returned has the ending newline removed.

Basic Rules
Type the following code exactly and save it with the name, cmndln.php, in the c:/Apache24/htdocs directory.

<?php

    $line;

    while (1)
        {
            echo "Mysql>";
            $line = readline();
            preg_replace ("/\s*;\s*$/", "", $line);
            preg_replace ("/^\s*/", "", $line);

            echo $line, "\n";

            if (preg_match ("/quit/i", $line))
                {
                    echo "Bye", "\n";
                    break;
                }
        }

?>

Go to the console (command prompt) and at the root directory, type the following and press the Enter Key:

    c:/PHP/php c:/Apache24/htdocs/cmndln.php

You should see, Mysql> which is the command prompt of the tool (the cmndln.php file).

Type anything at this prompt and press the Enter Key.

You should see, what you have typed, re-displayed. You should still see the tool prompt. To quit the tool, type the following and press the Enter Key:

    quit

You should see the word, “quit” re-displayed and below it you should see, Bye; then the DOS prompt. At this point, you have quitted the command line tool and the tool is no longer operating.

Explanation of Basic Rules
I now explain the above code, stressing on the relevant rules. The code begins with the declaration of the variable, $line. This variable will hold anything that you type as input. Input to a command line tool is a line of text ending with the newline (\n) character. The \n character comes in, as a result of the fact that you press the Enter Key.

After that you have the while loop. The condition of the while loop is (1). This means it should iterate infinitely, unless some condition occurs within the loop (curly brackets), to break it.

The first line in the curly brackets is “echo "Mysql>";”, which prints the command prompt for the tool. While the tool is running, this prompt replaces the DOS prompt. When the tool stops running, you get back your DOS prompt.

After the command prompt for the tool has been printed, and while in the while loop, execution goes to the line, “$line = readline();” . Whenever execution of a program reaches a statement like this, the execution halts, and you see a flashing underscore, on the right of the tool prompt. Whenever text (short or long) is typed at the tool prompt, and the Enter Key pressed, "readline()" should return the complete text (without the key that represents the Enter Key, i.e. \n) to the variable it is assigned to. In this case, the variable it is assigned to is, $line.

In practice, the end of the input text may have ‘;’ and space before or after ‘;’. All input text end with \n. The input text is a string. The next line in the code, “preg_replace ("/\s*;\s*$/", "", $line)” removes any space, any ‘;’ (and any \n) at the end of the input string. The line following, removes any space at the beginning of the input string. Such spaces are accidentally typed in, by the user.

The next line, “echo $line, "\n";” displays the input text without any unnecessary delimiting characters.

Now, because of the condition, (1) of the while loop, the while loop should iterate infinitely. However, when the user types “quit” without the quotes, at the tool prompt, the last code segment will break the while loop and put an end to the running of the program. It does this as follows:

The last code segment in the while loop is an if-statement. The condition of the if-statement is, “preg_match ("/quit/i", $line)”. This checks whether the input text is, “quit”, letter casing does not matter. If it is, then the loop has to be broken. In PHP, you break a loop with the statement, “break;”. Before “break;” is executed, the string, “Bye” is printed.

Yes, I told you it was easy; that is right. It is simple! Above are the basics of producing a PHP command line tool. Other features like including files, are the same as with non-command line tools, which you learn in this volume of tutorials.

That is it, for this part of the series. We stop here and continue in the next part.

Chrys


Related Links

Basics of PHP with Security Considerations
White Space in PHP
PHP Data Types with Security Considerations
PHP Variables with Security Considerations
PHP Operators with Security Considerations
PHP Control Structures with Security Considerations
PHP String with Security Considerations
PHP Arrays with Security Considerations
PHP Functions with Security Considerations
PHP Return Statement
Exception Handling in PHP
Variable Scope in PHP
Constant in PHP
PHP Classes and Objects
Reference in PHP
PHP Regular Expressions with Security Considerations
Date and Time in PHP with Security Considerations
Files and Directories with Security Considerations in PHP
Writing a PHP Command Line Tool
PHP Core Number Basics and Testing
Validating Input in PHP
PHP Eval Function and Security Risks
PHP Multi-Dimensional Array with Security Consideration
Mathematics Functions for Everybody in PHP
PHP Cheat Sheet and Prevention Explained
More Related Links

Cousins

Comments