Jump to content

Archive:PHP and MySQL Programming/Command Line Programming

From IdeaWazaWiki
Revision as of 16:11, 15 July 2006 by wikademia>Jguk

TOC


Introduction

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 appliations from the constraints of the internet browser. Now, PHP is being used to write GUI applications as well as command line appliations. We shall now look at writing PHP applications for the command line.

Getting the PHP-CLI

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 http://www.php.net/ for more help.

Initial Considerations

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

#!/bin/php

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

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 usefull function to get user input :

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

Output Formatting

The main consideration to make when formating output in command line programming as apposed to generating HTML output is that a new line is not created by a
tag, infact, 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 usefull funtion when doing command line programming is this :

<?
function output($message){
   print $message."\n";
}
?>


<< 5. Session Handling | TOC | >> 7. Form Handling