PHP and MySQL Programming/Command Line Programming

PHP was traditionally used to help web administrators automate various mundane tasks and to add dynamism to the web pages. However, PHP (in its modern incarnation) is capable of much more. It is now being used in ways traditional programming languages are used. It is now possible to remove PHP applications from the constraints of the Internet server. Now, PHP is being used to write GUI applications as well as command line applications. We shall now look at writing PHP applications for the command line.

Getting the PHP-CLI edit

If you are running Linux, you should get the corresponding package for the PHP-CLI. In Debian, it is just a matter of typing:

$> apt-get install php5-cli

In Windows, the CLI should be included with the PHP files. Refer to and for more help.

Initial Considerations edit

We start off our command line applications with the following line:


Note: You do not include this line in Windows!

This should be the first line of the file, as it tells Linux which interpreter to use for the file.

The next thing you should do, is to make the file executable. This is done by the following Unix command:

chmod +x filename.php

Getting Keyboard Input edit

In order for us to retrieve keyboard input from the command line, we will need to use a little trick. Basically, we create a file handler to a special file called the Standard Input.

Here is the code to create this file handler:

$stdin = fopen("php://stdin", 'r');

We can now use $stdin just as if it were a normal file that we had opened for reading. (We obviously could not write to it, as it is Standard INPUT).

Here is a useful function to get user input:

 function getinput(){
    $stdin = fopen("php://stdin", 'r');
    $input = fgets($stdin, 1024);
    $input = trim($input);
    return $input;

Output Formatting edit

The main consideration to make when formatting output in command line programming as opposed to generating HTML output is that a new line is not created by a
tag, in fact, any HTML tags you put into the output, will simply be displayed as plain text.

In order to create a new line in the command line, we need to use a control character, \n . Another useful function when doing command line programming is this:

 function output($message){
    print $message."\n";

External Resources and Links edit

PHP CLI - ALL about running PHP script from command line: tutorials, options, examples, PHP CLI and PHP CGI difference.