Give it a search

Friday, December 10, 2010

Development – User Interfaces

The user interface is the part of the system that the users come into contact with. Hence their judgment heavily depends on the condition of the user interface. A system can meet its downfall if its user interfaces were not properly designed, Even if the system comprises of powerful and helpful logical functionalities. From the point of view of the user the system earns lot of plus marks if the user interfaces are properly designed and developed.

Most of the time, someone can misunderstand this as providing flashy interfaces. However this is not true. When it comes to user interface design “Simplicity Sells”.

Basically what is expected from a proper user interface design and some good practices to be adhered to when designing user interfaces is as follows.

  1. Providing information to the user in an uncluttered and easy to understand manner.
  2. Not stressing the eyes of the user.
  3. Avoid the usage of certain colour combinations as they can be unrecognizable by certain individuals with sight disorders.
  4. Avoid the usage of colours that can generate mental imbalances in certain individuals.
  5. Limiting to few of selected colours rather than using a wider range of colours which sometimes can be a burden on the users and even the computer.
  6. Be simple as possible and design controls that need higher priority to stand out from the rest of the user interface. This will avoid the user from being frustrated by having to figure out which is which.
  7. Use fonts that read clearly and use font colours that stand out from the background.
  8. When describing the usage of a control try to stick to the mindset of the user. Use a language that the user will understand clearly and avoid using technical notations as much as possible.
  9. Avoid the usage of words that can mean two things at the same time.
  10. Check the user interface for spelling mistakes for this can sometimes lead to complicated situations.


When designing user interfaces for this system a somewhat radical approach was used. That is the heavy utilization of Ajax. This is done to avoid the pages from constantly refreshing themselves for each and every request to the server, And also to avoid the browser from constantly reloading the same resource from the server or from the cache. In addition to that, usage of Ajax gave the distinct advantage of reduced network traffic which resulted in a distinct performance gain.

As described earlier, the system was designed in such a manner that it can be implemented as a collection of modules. Each of these modules had a user interface and this user interface was comprised of two parts, the HTML page and the Module Specific JavaScript file (the structure of the system is described in [link]). Only a handful of colours were used. Black, A darker shade of Red, Several shades of Gray and White were the only colours to be utilized.

Here are several of user interfaces used in the system.


The Main page

The most important part of the user interface was the “Main” page. This was the page that loaded when a user logs in to the system. This page was designed to be an anchor point for the whole system. In other words that is to say that this page will facilitate all other subsequent operations of the system.

The objective was to load all other modules within the Main page. And the main page was given the ability to load modules by the implementation of a menubar. The Figure illustrates a module loaded inside the Main Page.


Application module loaded inside the Main page


The menubar itself was loaded according to the privileges that have been granted to the user who is logging in. This method avoided users from trying to gain access to modules that they are not suppose to use. And also cross communication between modules in the user interface layer was banned so to avoid a privilege collision from happening.


Even from the early stages of requirement gathering users were asking for an interface that uses less amount of scrolling to navigate around. The system interfaces were designed bearing that in mind. And the outcome of it was a Main page that occupied the whole screen when it is running. Horizontal scrolling was also banned from the Main page.

Wednesday, December 8, 2010

Development - Using Ajax

Ajax, which stands for Asynchronous JavaScript and XML, is a method that enables web sites and web applications to communicate asynchronously with the server.

Well, it does sound a mouthful. Doesn’t it?

To explain what Ajax is first let’s talk about how a web site works. The method web sites work is called client-server architecture. In this the client is your web browser and the server is your web server. The client asks for a web page from the server and the server sends the requested page to the client. In early days, when you ask for a web page, the client request for that whole page from the server. This means that you will have to wait staring at a blank screen until the page loads which is a boring thing to do and a complete waste of time and bandwidth. This is where Ajax came in. Ajax enabled web pages to load in parts and send requests behind the scene enabling a web page to request only the required data from the server to update its appearance and information. Nowadays web sites use Ajax frequently to deliver a seamless user experience.

There are several ways that you can implement Ajax to a web site. In this project I have used the “XMLHttpRequest” object.

This is how the request object was created using JavaScript. The implementation of XMLHttpRequest object differs depending on the browser. That is why an “if” statement block is used.

/*
* create the request object
*/
function ajaxObj()
{
    var ajaxCall = false;

    if(window.XMLHttpRequest) //check whether the browser is Firefox
    {
        ajaxCall = new XMLHttpRequest();
        ajaxCall.overrideMimeType("text/xml");
    }
    else if(window.ActiveXObject) //check whether the browser is IE
    {
        ajaxCall = new ActiveXObject("Microsoft.XMLHTTP");
    }

    return ajaxCall;
}


After creating the Ajax object you can send asynchronous requests to the server using it. Here is the code for that. This function takes the following parameters.
dataSource – The page that you wish to call asynchronously
ajaxCall – Ajax object created using the above ajaxObj() function.

/*
* communicating with the server asynchronously
*/
function getData(dataSource, ajaxCall)
{
     // The GET method is used here. Also can use the POST method with little
     // modification to the code
     if(ajaxCall)
    {
       ajaxCall.open("GET", dataSource);
       ajaxCall.send(null);
    }
}


Finally this is how you tie all these up to get the job done. The following code is used to load HTML content asynchronously from the server to dynamically change the appearance of the user interface.

This function takes the following parameter.
formName – Name of the HTML content file that is to be loaded

/*
* load forms dynamically
*/
function loadForm(formName)
{
    var ajaxCall = ajaxObj();

    getData("./ui/forms/" + formName, ajaxCall);

    ajaxCall.onreadystatechange = function()
       {
           //show a message while loading
           if(ajaxCall.readyState == 3)
           {
                var target;
                target = document.getElementById("divMain");
                target.innerHTML = "Loading…"        
}
           if(ajaxCall.readyState == 4 && ajaxCall.status == 200)
           {
                target = document.getElementById("divMain");


                //get form data
                var formContent = ajaxCall.responseText;

                //display form
                target.innerHTML = formContent;
           }
       }
}

Wednesday, December 1, 2010

Development – Automatic Number Generation

The system required to generate serial numbers for Users, Applications, Clients and for many other records. These serial numbers were supposed to follow a certain format; they should have a defined character width; and also they should comprise of two parts (the prefix part and the incrementing numeric part).

For an example, the serial number for an application should look like this.

APP000001
 
In this, the “APP” part is the prefix for Applications. The “000001” is the incrementing numeric part.

For generating auto incrementing numbers the easiest way is to use “Auto increment” facility in MySQL. However that facility cannot be used to create serial numbers this complex.

So here’s what I did. This method is inspired from a project that I participated a few years back.

The auto number generator uses data from a table called “sys_autono”.
 
ER Diagram for the sys_autono table


The table that has been filled with data looks like this.


sys_autono filled with data - powered by phpMyAdmin


Here is the code to generate serial numbers. You can find the DBAdapter class in Development – Database Connection and Transaction Management

require_once($_SERVER['DOCUMENT_ROOT'] . '/FixedDeposit/adapters/DBAdapter.php');

/**
* Get the current auto number from the database.
* @param $prefix String Prefix for the auto number
* @return String Auto number or an error message if the auto number
* generation faild
*/

function getAutono($prefix)
{
        $DBAdapter = new DBAdapter;
   
        $query = "SELECT AUTO_pre_name, AUTO_current, AUTO_length
                        FROM sys_autono
                        WHERE AUTO_prefix = '$prefix'";

        $result = $DBAdapter -> runQueryDirect($query);


        $autoPreName; //prefix name
        $autoCurrent; //current number
        $autoLength; //length of the auto number

        if($result)
        {
            while($row = mysql_fetch_array($result))
            {
                $autoPreName = $row["AUTO_pre_name"];
                $autoCurrent = $row["AUTO_current"];
                $autoLength = $row["AUTO_length"];
            }

            //generate the auto number
            $autoNumber = $autoPreName . str_pad($autoCurrent, $autoLength, "0", STR_PAD_LEFT);
            return $autoNumber;
        }
        else
        {
            return "Error - Auto number not found";
        }
}


Now, after you create one serial number and used it you have to update “sys_autono” so the above function will not create the same number again. The following function is used to do so.

function updateAutono($prefix)
{
        $DBAdapter = new DBAdapter;
   
        $query = "UPDATE sys_autono
                    SET AUTO_current = AUTO_current+1,
                        AUTO_rec_date = curdate(),
                        AUTO_sync = 'N'
                    WHERE AUTO_prefix = '$prefix'";

        return $DBAdapter -> runQueryTrans($query);
}


When you want to generate a serial number all you have to do is this. Call “getAutono” method with the prefix name as the parameter.

$autono = getAutono("APP");

Then you can use that number for the required purpose. And afterwards update the auto number table by calling updateAutono with the prefix name as the parameter.

updateAutono("APP");

Tuesday, November 30, 2010

Development – The Database

The database was also designed as two parts namely the “System” part and the “Business” part. System portion of the database was designed to hold data that is vital to system functionality but has less use when it comes to business functionalities. For that purpose the Business portion of the database was designed. This design approach enabled the separate development of system driving logic and business process driving logic.



System

Contains data required for system level functionality. This mainly includes User management and User privilege management.

The Entity Relationship (ER) diagram for the system part is as below.






Logic


Contain data for dealing with business logic (in this case, Fixed Deposit management process) and logic for creating reports.

The ER diagram for the logic part is somewhat extensive. So I’ll just give the list of tables here with a brief definition stating the use of each table.


  • lgc_address (Address information)
  • lgc_application (Fixed Deposit application information)
  • lgc_bank (Bank information)
  • lgc_bank_branch (Bank branch information)
  • lgc_certificate (FD certificate information)
  • lgc_city (City information that will be used in addresses)
  • lgc_client (FD client information)
  • lgc_client_type (FD client type information)
  • lgc_cl_cl_type (Client to client type mapping)
  • lgc_district (District information that will be used in addresses)
  • lgc_employment (FD client employment details)
  • lgc_eod (Data for End of the Day process)
  • lgc_interest_rates (FD interest rate information)
  • lgc_interest_schedule (FD interest schedule information for an application)
  • lgc_payment (FD payment details)
  • lgc_payment_schedule (FD payment schedule information for an application)
  • lgc_province (Province information that will be used in addresses)
  • lgc_receipt (FD receipt information)
  • lgc_renewals (FD renewal information)
  • lgc_withdrawals (FD withdrawal information)

Tuesday, March 23, 2010

Development – Database Connection and Transaction Management

The system uses MySQL as the DBMS to store data regarding the fixed Deposit management process as well as some fundamental system information.

So a php script was needed to access and manipulate the database. There also was the need to manage transactions in the database so that the database will be consistent.

These two requirements were addressed by the DBAdapter class. It was developed to allow the system to access the database and to do transactions to the database in a centralized manner. In other words all other scripts that require database access will use this class to gain it.

This way allows better control of database management because of several reasons.

  • Since the system is using one class to access the database DB access scripts won’t scatter all around the source code, thereby giving the programmer a much easier time when it comes to reconfigure the DB connection.
  • This will also reduce the amount of code because of code reusability.

Actually DB access is achieved using 3 class files (DBAdapter, FileAdapter, XMLAdapter) and 1 XML file (dbconfig.xml).


Why so many classes?

Well, first of all let me explain how a connection is made to the database.

All credentials for accessing the database such as Host, User, Password and Database Name are stored in the dbconfig.xml.

So to get those values from the XML first you need to read the file (FileAdapter is used). Then you need to read each XML element (XMLAdapter is used) then you can make the connection (DBAdapter).


Then why can’t you write one class to do all these?

Well, you can. But then, what if you wanted to read a different kind of file to do something else? Then you will have to write code to open and read files all over again. When you create large systems you have to consider the big picture. That is why these functionalities are divided into several classes. Code reusability can be achieved. And that will definitely improve the clarity of the code.

The code looks something like this for accessing the database.

Note: Only the necessary methods of each class are given below.



class FileAdapter
{

/**
*Open the file
*/
function openFile($fileName, $accessMode)
{
$fp = fopen($fileName, $accessMode) or die("Error opening file");
return $fp;
}

/**
*Close the file
*/
function closeFile($pointer)
{
if($pointer)
{
fclose($pointer);
}
}

/**
*Read the file and store data in a variable
*/
function readFile($fileName)
{
$fp = $this -> openFile($fileName, "r"); //file mode “r” means read

$data;

if($fp)
{
while(!feof($fp))
{
$data .= fgets($fp, 4096); //get one line at a time
}
}

$this -> closeFile($fp);
return $data;
}
}



//imports___________________________
require_once('FileAdapter.php');
//_________________________________

class XMLAdapter
{
/**
*Open the xml file and get the content
*/
function getXMLContent($fileName)
{
if($fileName != "" && substr($fileName, -3) == "xml")
{
$FileAdapter = new FileAdapter;
$xml = $FileAdapter -> readFile($fileName);
return $xml;
}
else
{
return false;
}
}

/**
*Get the content into an array of XML tags
*/
function getXMLTagArray($fileName)
{
$FileAdapter = new FileAdapter;
$xml = $FileAdapter -> readFile($fileName);

//Create an XML parser
$xmlparser = xml_parser_create();
xml_parser_set_option($xmlparser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($xmlparser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($xmlparser, $xml, $arrValues);
xml_parser_free($xmlparser);

return $arrValues;
}


/**
*Get values in XML tags to array variables
*/
function getXMLData($fileName)
{
$arrTemp = $this -> getXMLTagArray($fileName);
$arrValues = array();

foreach($arrTemp as $arrSub)
{
if($arrSub['type'] == "complete")
{
$arrValues[] = $arrSub['value'];
}
}

return $arrValues;
}
}



//imports__________________________________
require_once('XMLAdapter.php');
//_______________________________________

class DBAdapter
{

/**
*Connect to the database
*/
function connect()
{
//Get connection info from the config XML
$XMLAdapter = new XMLAdapter;
$db = $XMLAdapter -> getXMLData($_SERVER['DOCUMENT_ROOT']."/FixedDeposit/config/dbconfig.xml");

$server = $db[0];
$user = $db[1];
$password = $db[2];
$dbName = $db[3];

//Establish connection
$connection = mysql_connect($server, $user, $password) or die(mysql_error());
mysql_select_db($dbName,$connection) or die(mysql_error());

return $connection;
}


/**
*Close connection
*/
function close($connection)
{
if($connection)
{
mysql_close($connection);
}
}

/**
*Start a new transaction
*/
function begin($connection)
{
mysql_query("BEGIN", $connection);
}

/**
*Commit a transaction
*/
function commit($connection)
{
mysql_query("COMMIT", $connection);
}


/**
*Rollback a transaction
*/
function rollback($connection, $terminate = false)
{
mysql_query("ROLLBACK", $connection);
if($terminate)
{
$this -> close($connection);
}
}


/**
*Run query without transaction control
*/
function runQueryDirect($query)
{
//connect
$connection = $this -> connect();

//run query
$result = mysql_query($query, $connection) or die(mysql_error());

//close connection
$this -> close($connection);

return $result;
}


/**
*Run query with transaction control
*/
function runQueryTrans($query)
{
//connect
$connection = $this -> connect();

//start the transaction
$this->begin($connection);

//run query
$result = mysql_query($query, $connection);

//check for success
if($result)
{
//commit
$this->commit($connection);
}
else
{
//rollback
$this->rollback($connection);
}

$this -> close($connection);

return $result;
}
}

Wednesday, March 17, 2010

The Design of the System


The Fixed Deposit Management System was designed as a web application. Following technologies will be used in the development of the system.
  • php
  • HTML
  • CSS
  • JavaScript
  • XML

When designing the system several important decisions were taken. They are listed below.

1. The system was divided into three fundamental layers and each type of functionality was allocated in those separate layers. All the interfaces and interface driving logic was allocated to the “Presentation Tier”. Fundamental logical operations were placed in the “Logic Tier” and the database was placed in the “Data Tier”.
This is technically known as the three-tier architecture and is widely used in web applications.

2. System was to be designed as separate modules. And a base on which all of those modules can be put together. Each module needed to be as separate as possible with other modules. This was to enable the system to be developed and implemented in sections rather than to develop everything in one go. And also to ease future modifications.

3. It was seen that implementation would be much easier if an Object Oriented approach was used. The business process then could be easily simulated inside the computer. Additionally, by using object orientation code reusability and abstraction could be achieved.

4. It was decided to divide the system logically into two parts. These two parts were named as "System" and "Business" The "System" portion of the system comprised of fundamental functionality that was essential to the system. These included.

  • User authentication
  • Privilege granting for users
  • Module handling
  • Accessing resources beyond the system boundary
  • Database connection handling
  • File handling
  • XML parsing

On the other hand the "Business" portion contained all the business logic that was needed in maintaining fixed deposits.

5. A minimum amount of business logic was to be allocated inside user interfaces. This gave the ability to completely change the user interface without changing the actual business logic.


The overall design of the Fixed Deposit Management System can be illustrated as follows.





The system comprised of modules and a base that connects all modules together.
Logic was distributed all over the system. This was to achieve distributed computing and to reduce the computational load of the server by doing so. The scattering around of logic all over the system was done adhering to several fundamental conditions.

They are as follows.

1. System and Business logic that are vital to the system was kept in the server
2. Validations and low priority operations were moved to the client side.



Adapters

Adapters are a collection of php classes. The objectives of these are to facilitate access to resources such as the Database, Files, XML documents and third party libraries that reside outside of the system boundary. All other logic classes in the system are given access to outside resources only through an adapter class. As an example a logic class needs to instantiate the adapter class that facilitate database operations in order to connect and run transactions in the DBMS.

Adapter classes facilitate abstraction, code reusability and ease of maintenance. Since these classes provide centralized access to a resource the system gains the distinct advantage of portability.


Common JavaScript Files

These files contain common operations shared by the system’s client side.


CSS

These are a set of Cascading Style Sheet (CSS) files. Their objective is to keep the styling data of the interfaces separate from interfaces themselves. This was done to avoid spending too much time designing user interfaces and also to gain the ability to change the appearance of these interfaces depending on user feedbacks.


Module

A Module accomplishes a unique task within the system. As an example the Client module handles insertion of new clients and updating and deletion of existing clients.
A single Module consists of four files. Two at server side (Logic and Link) and two at client side (Module specific JavaScript and HTML).


HTML Page

This is the user interface for the module


Module Specific JavaScript File

This file handles all of the user operations done on the HTML page. Allow the server side of the module to communicate with the client side and handles data transfer between the server and the client asynchronously. On top of all that this file takes on the job of modifying the interface according to response from the server.


Link File

Link file is a php script file that acts as the bridge between the client side JavaScript file and the server side logic file. Addition of this portion to a module was needed to overcome the heterogenic situation that arises when two different programming languages try to communicate with each other.


Logic File

The Logic file of the module is a php class. All of the vital module specific logic resides within this class.


XMLHTTPRequest

This is a JavaScript file that creates the XMLHTTPRequest object. This object is solely responsible for the asynchronous communication between the client and the server. This is more commonly known as a popular form of Ajax implementation.

Monday, March 15, 2010

The Scope of the Project

The project was to create a Fixed Deposit Management System.

Before starting to describe how the problem was addressed I will briefly discuss what a Fixed Deposit is.


Fixed Deposit

A Fixed Deposit is an investing mechanism where an individual can invest his or her money in a financial company for a fixed period of time. An interest is given by the company to the investor depending on the amount of money and the period of investment.

There is a formal procedure that is followed during this process. The process involves lot of referencing and cross validating. Hence carrying it out manually can sometimes be a burden on employees. Especially, when there are a large number of customers to be managed.
The fixed deposit management process varies by country. This is due to the fact that laws and regulations for financial transactions differ according to the country. And further more each financial institute has their own variation when doing fixed deposits.

1. An application form is given to an investor to be filled and then handed over to the corresponding officer. This application consists of following details.
  • The details of the investor who is known as the “Holder” in Fixed Deposits. There can be up to 3 Holders for a Fixed Deposit.
  • The details of the “Nominee”
  • Details of “Payee”. There can be up to 3 Payees.
  • The deposit amount
  • The deposit period
  • Deposit type (“Monthly” deposits pay interest by month and “Maturity” deposits pay interest at the end of the period)
2. The application is then checked by that officer. If relevant conditions are satisfied then a draft version of the Fixed Deposit is started by that officer.

3. The agreed amount of money is paid by the customer to the company and the company issues a receipt

4. If the money was paid via a cheque, the cheque is checked for validity and if valid the fixed deposit is “Initiated”. Or if the payment was made by cash then the Fixed Deposit is “Initiated” as for validation is not required.

5. A Fixed Deposit Certificate is printed and handed over to the Holder.

6. All initiated applications are forwarded to a superior officer and is again checked.

7. If conditions are satisfied the Fixed Deposit is “Approved”.

8. Monthly interest is calculated and paid to the investor appropriately.

9. When a Fixed Deposit is “Matured” (time period for the Fixed Deposit completed) the investor is given the opportunity either to “Withdraw” the deposit or to “Renew” it.

10. In some cases the investor might want to withdraw the money before the Fixed
Deposit matures. This is known as a “Pre-Mature” withdrawal and handled according to a different process. Then the interest is recalculated using a different formula that yields interest at a much lower rate to the time the money staid with the company.

  • If the FD is of “Maturity” type then the deposit amount plus the newly calculated interest is given to the investor
  • If the FD is of “Monthly” type where the investor has claimed the interests of previous months, that amount is deducted from the combination of the deposit amount and the newly calculated interest amount.

For better understanding the whole process can be illustrated as follows





Objectives of the Project

Having explained what a Fixed Deposit is, following were the main objectives of the project.

1. Customer details and details regarding Fixed Deposits needed to be held in digital format for easy access and maintainability

2. Interest that should be given to an investor needed to be calculated along with the interest payment date. These interest calculations needed to be done considering several factors
  • The deposit amount
  • The period of deposit

3. Fixed Deposit certificates and receipts needed to be printed

4. The entire process of managing fixed deposits must run as a smooth work flow

5. Detailed reports and statistics were needed for the management to take vital management decisions.

6. Management of Fixed Deposits needed to be faster. Hence the company can deal with more customers.

7. The staff needed to be relieved of burdensome operations such as constant cross validating and the need to go through files upon files of records.

Sunday, March 7, 2010

Additional Tools Used

Apache HTTP Server, php and MySQL created the fundamental environment for the project. Apart from these several other tools were used to streamline and ease the development of the system.


NetBeans IDE


The NetBeans IDE is a free integrated development environment that supports an exquisite range of programming languages and development environments. It is one of my favourite IDEs and it helped me a lot in the development process. Especially the code completion and the ability to refer the php manual from within the IDE came very helpful.

Official Website http://www.netbeans.org/



phpMyAdmin

To manage the MySQL database I used phpMyAdmin. It too is free and open sourced and great for managing MySQL.



Firefox

I used this popular free web browser as the client side for my system. The system was developed targeting only Firefox. Why? It is to avoid coding JavaScript separately for each browser. This was not seen as a weakness of the system but as one of the strong points (coding JavaScript for just one browser actually helped me in time management for the project). Since the system will only be used in a contained environment all the computers in the company could be equipped with Firefox to access the system.



Firebug

Firebug is a JavaScript debugging plugin that comes for Firefox. Since the system uses JavaScript and Ajax a lot, I needed a way to debug JavaScript and Firebug was the solution. It can be downloaded from its web site or it comes attached with NetBeans. This is a great tool that can really ease the pain when it comes to JavaScript debugging. And not only that, you can use FireBug to monitor asynchronous calls to the server.


Friday, February 12, 2010

Downloading and Installing php 5

Downloading php

To download php, visit www.php.net. This is the official php site. And go to Downloads. In the download section go to Windows Binaries. You have two options. Either you can download the installer package or you can download the zip package. Don’t go for the installer package because it will only configure IIS and not Apache. Download the zip package.



Installing php


Extract the php zip package to a folder in your computer.

You will notice that php 4 and php 5 are slightly different at the first glance of the directory content. So to install php 5 the method too is slightly different. Mostly you can use the steps in installing php 4 to install php 5. But there are several exceptions. That is why I write this blog entry separated from php 4 installation steps. Differences in the php 5 installation from php 4 installation are in different text colour in this blog entry.

Make sure you extract the zip file into a folder with the folder name not having spaces. This is very important because otherwise you will have some configuration problems when you are trying to configure php with Apache.

Open the “install.txt” file in the php folder.
Go to the “Installing as an Apache module” section and follow the instructions in there.

Or you can directly do this. But it is always better to have a look at the “Installing as an Apache module” section in the “install.txt” file.

OK, let’s assume that you have php 5 and you extracted the contents of the zip file into C:\php.

Now, open the Apache httpd.conf file (Start > All Programs > Apache HTTP Server 2.0.54 > Configure Apache Server > Edit the Apache httpd.conf Configuration File)
Go to the “LoadModule” block and add this line to the end.

LoadModule php5_module C:/php/php5apache2.dll

And to enable Apache to recognize and handle php files add the following line to the “AddType” section.

AddType application/x-httpd-php .php

Now save the file and restart the Apache server.



Configuring The php.ini File

This is where php 5 installation differs from php 4 installation. Although you can gain access to MySQL module without configuring the php.ini file in php 4, you have to configure the php.ini file in order to gain access to MySQL module in php 5
Here is how
In your php directory (ex. C:\php) there is a file called “php.INI-RECOMMENDED”. First make a copy of it in the php directory. And then rename the copy of “php.INI-RECOMMENDED” in to “php.ini”. It is very important that you don’t use the original “php.INI-RECOMMENDED” for configurations.

Now open the Apache httpd.conf file (Start > All Programs > Apache HTTP Server 2.0.54 > Configure Apache Server > Edit the Apache httpd.conf Configuration File)
Add this part to the very bottom of the file

# configure the path to php.ini
PHPIniDir "C:/php"

Note: This directive only works for Apache 2 web servers and above. If you are working with an earlier version of Apache then you will have to use the PHPRC environment variable. Check out the install.txt in the php directory to know more about this method.
Save the file and restart Apache

Now right click on “My Computer” and select “Properties” from the popup menu. Then go to “Advanced” tab and select “Environment Variables”. Choose “Path” from “System variables” and click “Edit”.

Don’t delete the content of the “Variable value” text box (That’s very important).
Now find the part of the variable string that gives the path value for MySQL bin directory.
Then put the path of the php directory before the path of the MySQL bin directory. (You have to make sure that each of these path variables are separated with a “;”).
Remember! This is very important. Unless you do this, MySQL module will fail to load in php 5. This was the point that I stuck when I first tried to install php 5. And I am very thankful to the person who left a comment in the php web site telling why this happens and how to get around this problem.

Click “Ok” to save the changes and then restart your computer. This is done because changes to Environment Variables only take effect after restarting the computer.
Once all of these are done you can configure php using “php.ini”

Open “php.ini” in the php directory

This file is mainly used to dynamically load extensions for php. To do so first you will have to tell php where it can find these extensions. These extensions are in a directory named “extensions” inside the php directory. Give the path of this directory to “extension_dir” directive.

extension_dir = "C:\php\ext"

You are almost done

Now when you want to load a dynamic extension all you have to do is to go to the “Dynamic Extensions” section of the “php.ini” and uncomment the appropriate directive (remove the “;” from the beginning of the directive)

Like this

change

;extension=php_mysql.dll

to

extension=php_mysql.dll

You will have to save the file and restart Apache for these changes to take effect

Tuesday, February 9, 2010

Downloading and Installing php 4

Downloading php

To download php, visit www.php.net. This is the official php site. And go to Downloads. In the download section go to Windows Binaries. You have two options. Either you can download the installer package or you can download the zip package. Don’t go for the installer package because it will only configure IIS and not Apache. Download the zip package.



Installing php

Extract the php zip package to a folder in your computer.

Make sure you extract the zip file into a folder with the folder name not having spaces. This is very important because otherwise you will have some configuration problems when you are trying to configure php with Apache.

Open the “install.txt” file in the php folder.
Go to the “Installing as an Apache module” section and follow the instructions in there.

Or you can directly do this. But it is always better to have a look at the “Installing as an Apache module” section in the “install.txt” file.

OK, let’s assume that you have php 4 and you extracted the contents of the zip file into C:\php.

Open the folder named “SAPI” in C:\php.

Copy the file named “php4apache2.dll” in that folder and paste it in C:\php.
Now, open the Apache httpd.conf file (Start > All Programs > Apache HTTP Server 2.0.54 > Configure Apache Server > Edit the Apache httpd.conf Configuration File)
Go to the “LoadModule” block and add this line to the end.

LoadModule php4_module C:/php/php4apache2.dll

And to enable Apache to recognize and handle php files add the following line to the “AddType” section.

AddType application/x-httpd-php .php

Now save the file and restart the Apache server.



Configuring The php.ini File

When you have completed above steps, php will work without much of a problem. However there is another step to complete the installation. That is setting up the php.ini file. By doing this you can harness the full potential of php. Otherwise you won’t be able to load dynamic modules to support php.

Here is how

In your php directory (ex. C:\php) there is a file called “php.INI-RECOMMENDED”. First make a copy of it in the php directory. And then rename the copy of “php.INI-RECOMMENDED” in to “php.ini”. It is very important that you don’t use the original “php.INI-RECOMMENDED” for configurations.

Now open the Apache httpd.conf file (Start > All Programs > Apache HTTP Server 2.0.54 > Configure Apache Server > Edit the Apache httpd.conf Configuration File)
Add this part to the very bottom of the file

# configure the path to php.ini
PHPIniDir "C:/php"

Note: This directive only works for Apache 2 web servers and above. If you are working with an earlier version of Apache then you will have to use the PHPRC environment variable. Check out the install.txt in the php directory to know more about this method.
Save the file and restart Apache

Now right click on “My Computer” and select “Properties” from the popup menu. Then go to “Advanced” tab and select “Environment Variables”. Choose “Path” from “System variables” and click “Edit”.

Don’t delete the content of the “Variable value” text box (That’s very important). First add a “;” at the end of the content. Then add the path of your php directory after the “;” character (This is the divider that divides different system variables in the same string)

Click “Ok” to save the changes and then restart your computer. This is done because changes to Environment Variables only take effect after restarting the computer.

Once all of these are done you can configure php using “php.ini”

Open “php.ini” in the php directory
This file is mainly used to dynamically load extensions for php. To do so first you will have to tell php where it can find these extensions. These extensions are in a directory named “extensions” inside the php directory. Give the path of this directory to “extension_dir” directive.

extension_dir = "C:\php\extensions"


You are almost done

Now when you want to load a dynamic extension all you have to do is to go to the “Dynamic Extensions” section of the “php.ini” and uncomment the appropriate directive (remove the “;” from the beginning of the directive)

Like this

change

;extension=php_mysql.dll

to

extension=php_mysql.dll


You will have to save the file and restart Apache for these changes to take effect

Sunday, January 31, 2010

Downloading, Installing and Configuring Apache

PHP is a server side scripting language which means that all of the processing regarding to a php page is done on the server not on the client. If the browser has requested for a php page the web server then passes that request to the php Engine. PHP Engine is the part that handles processing of php pages. When php pages are processed in the php Engine they generate html pages, which then are sent to the browser. So you see that in order to get an output from a php page you need a Web Server.

What is a Web Server?

When you browse the Internet or any other web site your browser requests for web pages from another computer. This is known as a web request. The Web Server that resides in that computer identifies that a browser is requesting a web page and do the required processing and deliver the web page to the browser.

Now you have to understand this, a Web Server is not a Server. A Server is a high end computer whereas a Web Server is a program running on a computer that processes web requests. But both are referred to as Servers for convenience.

There are many Web Servers that you can use for this purpose such as
Microsoft IIS (Internet Information Server)



We will be using Apache as the Web Server. In fact many web hosts uses Apache for its reliability and configurability. And it’s free and open sourced.

If you need to know more about Apache please visit this page.

www.apache.org


Now let’s Download, Install and Configure Apache.

These steps are for the Windows platform.


Downloading Apache

The installation files for apache can be downloaded from www.apache.org.

Click HTTP Server under "Apache projects"

Download the HTTP Server installation (.msi) file for Win32.



Installing Apache

  • Once you have downloaded the installation file simply double click and launch it.

  • Click "Next"
  • Read and accept the license agreement to proceed and click "Next".
  • Read all of the instructions if you like to. Click "Next".

  • Since Apache is going to be used for development requirements put the following information.

    Network Domain: localhost
    Server Name: localhost
    Administrator’s Email Address: any email address

    Keep the recommended selection

  • Click "Next"
  • Keep the selection as “Complete” and click "Next".
  • Choose a path for the destination folder. You can keep the default path if you are OK with it. Click "Next".
  • Click "Install". Be patient while the apache server is being installed.


And that’s it.



Configuring Apache

Now when you open your browser and type http://localhost or 127.0.0.1 (This is the IP address for localhost for all computers) or the IP address of your computer you will get the following page.




Now you are seeing the default web page in the "htdocs" folder. Assuming that you have given the default path as the installation directory for Apache this will be at

C:\Program Files\Apache Group\Apache2\htdocs

The reason that you see the web page that is in htdocs is that Apache is configured to show you that folder when you browse to the network domain (in our case it is http://localhost).

You can put your web projects here and run them. But however this is not recommended.

Why?

Well, first of all you are in a directory that a program is saved to. When Apache is uninstalled or repaired for some reason you most probably will lose all the files saved inside htdocs. And when you delete and rearrange your own files within this folder there is the possibility that you might accidently delete or renames a file or a folder that is vital to the functionality of Apache.

The best thing to do is that you create your own folder somewhere else and configure Apache to that folder.

Here is how it is done.

Go to Start > All Programs > Apache HTTP Server 2.0.54 > Configure Apache Server > Edit the Apache httpd.conf Configuration File

You can also open this file by navigating to
C:\Program Files\Apache Group\Apache2\conf\httpd.conf

Once you opened the file scroll down and find this part.

#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "C:/Program Files/Apache Group/Apache2/htdocs"

Now let’s assume that you need “C:\Projects” to be your “Document Root” then you edit this part as follows.

#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
#DocumentRoot "C:/Program Files/Apache Group/Apache2/htdocs"
DocumentRoot "C:/Projects"

Note: Always remember to comment the line that you intend to change and add the changed line below the commented line. This way you will know exactly what you changed.


Then scroll down to find this part

#
# This should be changed to whatever you set DocumentRoot to.
#
Directory "C:/Program Files/Apache Group/Apache2/htdocs"

Change this part as follows

#
# This should be changed to whatever you set DocumentRoot to.
#
#Directory "C:/Program Files/Apache Group/Apache2/htdocs"
Directory "C:/Projects"

It is a good practice to backup the original httpd.config file before you start messing with it. And don’t delete any line from the file. Just comment it out. The "#" is used for commenting.

When you’re done, save the file and restart Apache. This is very important because all the changes that you made to the httpd.config will take effect only after restarting the service.

Now you can put an html file in to the folder you specified and then go to the browser and navigate to http://localhost to see the result.