IBM WebSphere Developer Technical Journal: Pair J2EE with PHP to implement a common Web application infrastructure

Enterprise Java™ applications deployed on IBM® WebSphere® Application Server and Web sites deployed in Apache, MySQL, and PHP environments have traditionally been considered competing, mutually exclusive solutions. However, you can run WebSphere and PHP together to match their relative advantages to your Web development requirements.

Share:

Introduction

The Apache, MySQL, and PHP (AMP) stack of technologies, and IBM middleware, such as IBM HTTP Server, DB2® Universal Database, and WebSphere Application Server, have traditionally been thought of as competing, mutually exclusive solutions to common Web application development challenges. Within the standard Web application model that consists of user interface, business logic, and data storage tiers, the open source community and IBM both offer an application to provide the services to support each specific role:

  • The Apache HTTP Server and the IBM HTTP Server vie for the static content Web server role.
  • PHP and the J2EE™ environment provided by WebSphere Application Server compete for the business layer.
  • MySQL takes on DB2 UDB for the data tier.

However, it is becoming more common for individual software offerings from each group to be mixed with products from the other suite to fill each Web application role. For example, Develop IBM Cloudscape® and DB2 Universal Database applications with PHP shows you how to connect to DB2 from PHP applications, while Hosting PHP applications on the IBM HTTP Server shows you how to add PHP support to the IBM HTTP Server.

Situations where two software solutions that normally compete for the same role within a Web application coexisting within the same larger application are less common, but equally feasible. This article will show you that it is indeed possible to configure a single server with both WebSphere Application Server and PHP at the application layer in an environment where Apache is the Web server and DB2 UDB is the database.

Why would you want to do this?

Perhaps you need to open up an intranet application to the Web at large, or provide one or more flexible front ends to your data for different customers. Maybe you would like to try out an alternate platform without sacrificing your existing application infrastructure. It is fairly common to have two interfaces to a Web application consisting of a content management tool and the presentation logic for that data. You should feel able to choose the application layer best tailored for each part.

We will look first at the roles which compose a three-tiered Web application, and then match common implementation models to the project's requirements. We will choose specific middleware based on these business needs, then install and configure the software to support it. Finally, you will install the provided sample application in this environment and then run it.

The sample application

The sample code demonstrates a two-part Web application that models a cat adoption Web site. This tool and the fictional organization that it supports are hereafter referred to as the Catabase. The example consists of a Struts application deployed on WebSphere Application Server V5.1, which serves as the private content management tool for entering information by the Catabase team. A PHP 5 public site will display the content and enable users to search for animals based on their attributes. The database shared by both components is DB2 UDB Enterprise Server Edition Version 8.2. The Web server instance for both portions is Apache 1.3.

You should have a basic understanding of Web servers, server-side programming, and database design. Experience with the Jakarta Struts framework, PHP, and the Linux® command line is recommended.


Web applications 101

A Web application is a software system that uses a Web browser and the request/response model of the HTTP protocol as its user interface. Web applications serve to sell products, publish information, and Web-enable traditional applications, such as the human resources tools on a company intranet.

Most Web applications share a basic architecture consisting of three basic tiers:

  • A Web server to serve static content such as images, JavaScript files, and stylesheets.
  • An application layer to process business logic, like accepting orders or choosing content to display.
  • A back-end data store that holds persistent information and provides access to it based on privileges and rules.


A good metaphor to describe these roles is the restaurant scenario. In a simplified interpretation of this model:

  • The Web server is the waiter. When a customer places an order, the waiter goes off and returns it. He can return something "static" like a fork, or he can return something "prepared" on demand, such as a ham and cheese sandwich.
  • The application server is the cook. He or she accepts requests from the waiter to prepare something on behalf of a diner, and may need to consult other resources to get information on how to prepare the dish.
  • The database serves as the cookbook. It stores recipes and organizes them by category and index.

Web applications can be broken down further into categories depending on function and intended audience. Two groups are intranet-style Web applications and Internet-style Web applications, which are classified by their user base and development model:

Intranet-style Web applications

Intranet-style applications match the classic packaged application software model. They benefit from existing software design patterns that have affected program development for much of the last thirty years. These applications are release-driven and rely heavily on user sessions, data input forms and databases optimized for both reading and writing.

Development should take advantage of time-tested solutions and frameworks implemented over the past quarter century. These applications serve to process user data and treat every request as an important unit of work with a well-defined transaction lifecycle. Code release is oriented toward deployment of consolidated archives, which may contain deployment descriptors, component modules, and scores of supporting files.

In general, intranet-style Web applications:

  • Have well defined release cycles and versioning schemes.
  • Define very specific roles and processes responsible for deployment.
  • Employ enterprise design patterns forged over time.
  • Use third-party frameworks like Jakarta Struts, which excels at handling form-centric applications.
  • Have read/write, transaction-oriented databases.
  • Target a known browser vendor and/or release. The capabilities of the client are known in advance, or the intended audience is expected to use a specific user agent because the benefits offered by the application are critical, or the user is assumed to use the services often.

Internet-style Web applications

Internet applications, by contrast, are much more organic. Their relative lack of rigidity is bred of a quickly evolving medium brought about by the advent of HTML in the early 1990s. These applications focus on fast release cycles and excellent usability to attract and keep visitors. As such, they need quick response times, and should be planned by information architects and graphic designers who are able to evolve with industry trends.

These applications are file-centric and benefit from incremental deployments which have minimal impact on the operation of the server. Developers need very specific control over filenames to keep up with search-engine optimization trends and the semantic nature of the Web. Additionally, to optimize network traffic, the developer must have granular control over the size, format, and encoding of the output.

Internet-style Web applications:

  • Value file size optimization to conserve bandwidth.
  • Follow search engine optimization tactics.
  • Embrace successful design and usability trends.
  • Adapt to new browser capabilities and Web standards.
  • Are maintained by designers whose background is not programming-centric.
  • Require quick development, test, and deployment cycles.
  • Require incremental fixes or feature additions.
  • Use read-only or read-optimized data stores.

Introducing the Catabase

Like many common Web applications, the Catabase Web site has two distinct components to support its overall requirements. These components map to the intranet-style and Internet-style Web application models we described earlier:

  • A private administration system to manage the content used by the application.
  • A public area to display selected output to the public.

Our application requirements outline what the unified application needs to do and how it needs to be done.

  • Functional requirements for the content management tool
    Essentially, the Catabase needs to manage the attributes of cats and their relationships to humans. The Catabase administration team needs to enter and modify data to provide information on cats that are available for adoption by site visitors.
  • Non-functional requirements for the content management tool
    The Catabase administration tool needs to be secured by a password and available only to users who have administration duties. The integrity of human and cat data must be ensured. The overall management portion must be protected from intrusion at the network level.
  • Functional requirements for the public-facing site
    The site needs to provide easy access to information about cats available for adoption and the humans that serve as contacts, volunteers, and board members. Search functionality is required, as is syndication of featured animals to share information with affiliated Web sites and interested users.
  • Non-functional requirements for the public-facing site
    The site must be flexible and adapt easily to trends in Web functionality and design. If errors are spotted or users lodge complaints, the site must be updated with immediate, localized changes that do not interrupt current site visitors by restarting the server.

Selecting our tools

With our requirements clear, it is time to look at the middleware available to support each of the Catabase components.

When entering the architectural design phase of Web application development, project managers and developers alike have an interest in evaluating which software offerings will most efficiently fit the business requirements. The project manager should know what tools are available to fit the client's needs, how easy the tools are to work with given the development team's skill set, whether certain tools integrate with existing solutions, and -- of course -- how everything affects the bottom line. Developers need to know what tools are available to fit the task at hand, and should be aware of new tools that have become available and how they can enhance their current skill set and codebase with their innovations. Furthermore, knowledge of parallel approaches to common problems gives them a better understanding of their own solutions.

WebSphere Application Server V6
Although our sample scenario uses WebSphere Application Server V5.1, you should be able to apply these steps easily to a later version. The administrative console for WebSphere Application Server V6, for example, organizes its Resources, Security, and Environment sections differently from earlier versions, but If you are unable to find an option in the hierarchy indicated, use the Help link at the top of the admin console to search for it.

Benefits of WebSphere Application Server

Version 5.1 of WebSphere Application Server, which we are using in our example, provides Java 2 Enterprise Edition 1.3 (J2EE) capabilities, such as:

  • Compressed archive-oriented deployment units.
  • Well defined software lifecycle and deployment roles.
  • Application security through support for servlet filters.

Additionally, WebSphere is well suited for intranet-style application development because the integrated development environments (IDEs) of IBM WebSphere Studio Application Developer Version 5 and IBM Rational® Application Developer for WebSphere Software V6 provide built-in support for third-party frameworks like Struts. Both of these IDEs speed the development of quality applications that manage important data by offering advance debugging and code review functionality. Furthermore, these tools make adhering to enterprise application development patterns for J2EE easier.

Benefits of PHP

PHP promises quick development cycles because it is an interpreted language embedded in HTML files. There is no need to recompile these files to test them while developing; all that is needed is a browser refresh. Likewise, deployments of PHP scripts do not require a Web or application server restart.

Because PHP is supported on workstation operating systems such as Windows® XP, developers can use a range of code editors to write and test code, and can even deploy over (Secure) FTP or work on network shares from many of these tools.

Technology choices

Based on the strengths described above:

  • The intranet-style content management portion of the example application was built with the Struts framework supported by the J2EE 1.3 environment that WebSphere Application Server V5.1 provides.
  • As an integrated development environment, WebSphere Studio Application Developer Version 5.1 and Rational Application Developer V6 were used to develop and test the code.
  • For the public site, PHP 5 was chosen for its quick iteration turnaround and flexibility. This offered the most power, as it is expected that the front end of the application would change more often than the internal application. This also results in quick reaction to changing search engine optimization strategies, and bringing a team of developers up to speed easily. In addition, it provides us with an improved object-oriented framework and XML capability for our RSS feed.
  • Apache 1.3 is used for the Web server because it is well suited for integration with both of our application layers.
  • DB2 UDB is the shared database for both our applications.

PHP, WebSphere Application Server, Apache, DB2 UDB, and the Linux operating system can be considered middleware, which is a term used to describe software that provides the environment and services for the application that we are developing to meet the project requirements.

Next, we will outline the steps to get that environment set up and configured.

Intel EM64T or AMD64 systems

These installation notes assume an x86 32-bit PC platform. They have been known to work with 32-bit kernels on the x86_64 platform as well, though a few minor adjustments may be necessary. IBM does not currently offer an x86_64-bit WebSphere plug-in on its support site for use with an Apache Web server compiled on that platform. Additionally, compiling PHP on this platform will provide you with a shared object that is not compatible with the 32-bit version of IBM HTTP Server that supports WebSphere on this platform.


Install the middleware

Our architectural decisions determined which software we needed to support our application, and now it's time to install them. There are countless resources which document the installation of the individual middleware components that we need, but it is important to install the software in a particular order to support the example application:

The operating system

While the sample application and the software on which it will run are essentially platform independent, SuSE Linux Professional 9.2 is the operating system used in this article. A default installation of SuSE meets most of the application environment's needs, but there are a few important package groups to install and features to enable so that PHP and WebSphere Application Server can be installed and configured correctly later. (See the Appendix A README file in the download file for documentation on the particular installation used to test the Catabase application.)

  1. After choosing an Initial Installation there are a few subtasks that need to be configured in the Base Installation window. One of these is the Software section under the Installation Settings heading. From the Software Selection dialog, select the Detailed selection... button.
  2. In the resulting panel, make sure that the following Selections are checked:
    • C/C++ Compiler and Tools
    • Java
    • Experienced User
  3. In the Package Groups option of the Filter dropdown, expand the System and highlight Libraries. Make sure the following packages are checked:
    • libxml2
    • readline
  4. Also expand Development and highlight Libraries. Make sure the following packages are checked:
    • libxml2-devel
    • readline-devel
  5. After accepting the packages and groups above, the Software selections should now be:
    • Standard system with KDE
    • + Java
    • + KDE Desktop Environment
    • + C/C++ Compiler and Tools
    • + Office Applications
    • + Help & Support Documentation
    • + Graphical Base System
    • + Experienced User
    You can now proceed to accept the rest of the Installation Settings to perform the installation.
  6. When the installation has completed, you will be offered several Configuration options. To provide a unique host name for the system in its domain, you should change a few of the settings, so that the configuration looks like this:
    • Ethernet Adapter Configured with DHCP
    • Host Name: somehost.example.com
    • Name Servers: set by DHCP
    • Search List: set by DHCP
  7. Under the Network subtask, select Network Interfaces.
  8. In the Already configured devices pane, click the Change... button, then select Edit for the preselected device.
  9. In the Network address setup dialog, select the Host name and name server button.
  10. In the resulting dialog, change your host name and domain name, and uncheck the Change host name via DHCP box.
  11. For the rest of the operating system installation, you can choose the settings you need and let the installer complete the setup.
  12. After the system has started up for the first time, log in as root and create a directory called src for the installation files used in the next section.

    Listing 1. Prepare a directory to compile and install source code

    cd ~
    mkdir src

Using MySQL

You might choose to install the MySQL database server Version 4.1 at this point. Download the server and development libraries for use with PHP from MySQL. Later, include this code in your PHP configure line:
--with-mysqli=/usr/bin/mysql_config

The database

The Catabase application data store is DB2 Universal Database Enterprise Server Edition V8.2. The setup of DB2 is straightforward, but there are a few options that must be configured for it to support the application. (See the Appendix B README file in the download file for documentation on the particular installation used to test the Catabase application.)

  • Keep the Create a DB2 instance radio button checked during the Instance setup step.
  • Enter and confirm a password for the new db2inst1 user in the group db2grp1 during the Instance owning-user step.
  • Keep the Configure radio button checked and make note of the Port number value during the Instance TCP/IP step. The test environment used port 50001.
  • Keep the Authentication type dropdown at Server, and the Autostart the instance at system startup box checked during the Instance properties step.

The Web server

For the Web server to use HTTPS to protect user interaction with the Catabase content management tool, the Apache HTTP Server needs to be compiled with support for SSL. It must also be configured to listen on port 80 for HTTP and the 443 for HTTPS. (See Resources for the download location for OpenSSL, mod_ssl, and Apache.)

Apache versions and mod_ssl

The version numbers for each of the components listed will change over time. However, it is important that you match the second half of the mod_ssl version number to the version of Apache that you are installing. In this article, the number is 1.3.33.

  1. Place the source archives in the src directory you created earlier, and for each one, unzip and extract them using tar.

    Listing 2. Unzip and extract the source code folders.
    cd ~/src
    tar -zxvf openssl-0.9.7e.tar.gz
    tar -zxvf mod_ssl-2.8.22-1.3.33.tar.gz
    tar -zxvf apache_1.3.33.tar.gz
    tar -zxvf php-5.0.4.tar.gz
  2. OpenSSL is the cryptography library used for SSL communications, and is required by mod_ssl to encrypt HTTP traffic for Apache.

    Listing 3. Compile OpenSSL 0.9.7e
    cd openssl-0.9.7e
    ./config -fPIC 
    make
  3. Next, configure mod_ssl. Configuring mod_ssl adds information to the Apache source code. You may want to add other Apache configure flags here as well.

    Listing 4. Configure mod_ssl 2.8.22-1.3.33
    cd ../mod_ssl-2.8.22-1.3.33
    ./configure \
    --with-apache=../apache_1.3.33/ \
    --prefix=/opt/local/apache \
    --with-ssl=../openssl-0.9.7e \
    --enable-module=so \
    --enable-shared=max
  4. After configuring mod_ssl, you will be instructed to continue with the Apache installation.

    Listing 5. Configure Apache HTTP Server 1.3.33
    cd ../apache_1.3.33/
    make
  5. At this point, you will need to generate three Server Certification Files, which will be created based on the information you provide in response to five questions:

    Listing 6. Creating the server certification files
    make certificate

    • STEP 0: Decide the signature algorithm used for certificate
    • STEP 1: Generating RSA private key (1024 bit) [server.key]
    • STEP 2: Generating X.509 certificate signing request [server.csr]
    • STEP 3: Generating X.509 certificate signed by Snake Oil CA [server.crt]
    • STEP 4: Enrypting RSA private key with a pass phrase for security [server.key]

    Choose all the default options to the questions to create a self-signed certificate, and choose no to the last step, Encrypt the private key now?. When you have answered the questions, you should be presented with a message after the files have been created.

    Listing 7. The server certification files
    RESULT: Server Certification Files
    
    o  conf/ssl.key/server.key
       The PEM-encoded RSA private key file which you configure
       with the 'SSLCertificateKeyFile' directive (automatically done
       when you install via APACI). KEEP THIS FILE PRIVATE!
    
    o  conf/ssl.crt/server.crt
       The PEM-encoded X.509 certificate file which you configure
       with the 'SSLCertificateFile' directive (automatically done
       when you install via APACI).
    
    o  conf/ssl.csr/server.csr
       The PEM-encoded X.509 certificate signing request file which
       you can send to an official Certificate Authority (CA) in order
       to request a real server certificate (signed by this CA instead
       of our demonstration-only Snake Oil CA) which later can replace
       the conf/ssl.crt/server.crt file.
  6. Finally, you will complete the installation of Apache.

    Listing 8. Installing Apache
    make install
  7. If all went according to plan, you will see this message:

    Listing 9. Successful Apache installation
    +--------------------------------------------------------+
    | You now have successfully built and installed the      |
    | Apache 1.3 HTTP server. To verify that Apache actually |
    | works correctly you now should first check the         |
    | (initially created or preserved) configuration files   |
    |                                                        |
    |   /opt/local/apache/conf/httpd.conf
    |                                                        |
    | and then you should be able to immediately fire up     |
    | Apache the first time by running:                      |
    |                                                        |
    |   /opt/local/apache/bin/apachectl start
    |                                                        |
    | Or when you want to run it with SSL enabled use:       |
    |                                                        |
    |   /opt/local/apache/bin/apachectl startssl
    |                                                        |
    | Thanks for using Apache.       The Apache Group        |
    |                                http://www.apache.org/  |
    +--------------------------------------------------------+
  8. You should now start the server and confirm that it is running by loading http://localhost/ and https://localhost/ in your Web browser (Figure 1).
    Figure 1. Successful Web server installation.
    Successful Web server installation

Installing WebSphere Application Server

The installation wizard for WebSphere Application Server is easy to use, but if you run into difficulty getting it to launch on SuSE Linux:

  • The default installation does not include a copy of Netscape, so try linking to the path WebSphere Application Server is looking for with:
    ln -sf
    /usr/bin/firefox
    /usr/bin/netscape
    .
  • There is also an issue with the Java Virtual Machine thread stack size on both Red Hat and SuSE Linux systems. An easy way around it, usually signalled by a segmentation fault, is to issue ulimit -s 4096 before executing launchpad.sh.

The application layer

Here we install the core environments for the Catabase application: WebSphere Application Server and PHP. Both of these application environments will receive requests from Apache.

The setup of WebSphere Application Server V5.1 is straightforward, but there are a few options that must be selected to ensure we have configured it to support our application. (See the Appendix C README file in the download file for documentation on the particular installation used to test the Catabase application.)

  • Select the Custom radio button when the installer prompts you to choose either a Full install or a Custom install.
  • In the list of features pane, make sure that you have unchecked the Embedded messaging option and all of its children. Under Web server plug-ins make sure that you have checked Plug-in for Apache(TM) Web Server v1.3.
  • Enter or navigate to /opt/local/apache/conf/httpd.conf, which is the value we saw above when the installer prompts you for the location of the configuration file for Plug-in for Apache(TM) Web Server v1.3.

PHP 5 is the final piece of the puzzle and very easy to install. You might also choose to add other PHP configure flags as well (Listing 10). After you do so, then restart Apache (Listing 11).

Listing 10. Configuring, compiling and installing PHP 5.0.4
cd ../../php-5.0.4
./configure \
--prefix=/opt/local/php \
--with-apxs=/opt/local/apache/bin/apxs
--with-ibm-db2=/home/db2inst1/sqllib
make
make install

make test

You might choose to run make test before make install to run the PHP Quality Assurance Team's test cases on your PHP build.

Listing 11. Stopping and starting Apache with HTTPS
/opt/local/apache/bin/apachectl stop
/opt/local/apache/bin/apachectl startssl

Configure and test the middleware

Now that the software environment is installed, it's time to make some overall configuration changes to make sure that all the components are up and communicating properly.

Apache modules

While PHP and WebSphere have added the dynamic shared object (DSO) entries that they use to link to Apache to the configuration file, the three will not run without a few changes. The WebSphere plug-in entry needs to be moved above the PHP plug-in to work correctly. In addition, mod_ssl requires the EAPI version of the WebSphere plug-in. Finally, you will have to insert one more line of code:

  1. Open /opt/local/apache/conf/httpd.conf in a text editor and go to the end of the file. The PHP and WebSphere installations have added these lines:

    Listing 12. Incorrect httpd.conf LoadModule entries
    LoadModule app_server_http_module /opt/WebSphere/AppServer/bin/mod_app_server_http.so
    LoadModule php5_module libexec/libphp5.so
    WebSpherePluginConfig /opt/WebSphere/AppServer/config/cells/plugin-cfg.xml
  2. The WebSphere entries must be above the PHP entries, and you must change the mod_app_server_http.so entry to the EAPI version. Swap the order of the lines as shown in Listing 13, and move the whole block up to the end of the existing block of LoadModule directives.

    Listing 13. Corrected httpd.conf LoadModule entries
    LoadModule app_server_http_module /opt/WebSphere/AppServer/bin/mod_app_server_http_eapi.so
    WebSpherePluginConfig /opt/WebSphere/AppServer/config/cells/plugin-cfg.xml
    LoadModule php5_module libexec/libphp5.so
  3. Several lines below, after the list of existing AddModules, and right above the exising PHP 5 mod_php5.c entry, add this line:

    Listing 14. Added httpd.conf AddModule entry
    AddModule mod_app_server_http.c
  4. To instruct Apache to delegate certain requests to PHP, add an AddType directive, and include index.php as a recognized DirectoryIndex value. You can now save and close httpd.conf.

    Listing 15. New httpd.conf values
    AddType application/x-httpd-php .php
    DirectoryIndex index.html index.php
  5. To provide the environment variables PHP needs to connect to DB2, add this line to Apache's startup script, /opt/local/apache/bin/apachectl.

    Listing 16. New apachectl entry for DB2
    . /home/db2inst1/sqllib/db2profile
  6. Run the Apache configuration test and look for a Syntax OK result to make sure everything is in order.

    Listing 17. Confirm that the changes are syntactically correct
    /opt/local/apache/bin/apachectl configtest

Locking down the WebSphere administrative console

You can take advantage of several security options in the WebSphere Application Server admin console to secure it from unauthorized access. One option is to add users and authenticate them against the local operating system. You can only do this, however, if you are running WebSphere as root.

  1. Select System Administration => Console Users to add users.
  2. Select Security => User Registries => Local OS, and enter root and the password here.
  3. Select Security => Global Security and check the Enabled box. Uncheck the Enforce Java 2 Security box.
  4. Restart WebSphere Application Server, and you will now need a local operating system user ID and password to access the console, which will accessible over HTTPS.

WebSphere plug-in

Next, configure WebSphere Application Server through the administrative console to listen for requests from Apache on port 443, then restart it:

  1. Open http://localhost:9090/admin/ in a browser.
  2. Expand the Environment option and select Virtual Hosts.
  3. Select default_host under the list of items in the Virtual Hosts pane.
  4. Select Host Aliases under the Additional Properties section.
  5. Click the New button and enter the following values:
    • Host Name: *
    • Port: 443
  6. Select OK.
  7. Select Save in the Message(s) section.
  8. Click the Save button.
  9. Expand the Environment option and select Update Web Server Plugin.
  10. Select OK.

    Listing 18. Restart WebSphere
    ulimit -s 4096
    /opt/WebSphere/AppServer/bin/stopServer.sh server1
    /opt/WebSphere/AppServer/bin/startServer.sh server1
  11. Now, test the configuration. WebSphere Application Server V5 includes a sample application called Plants By WebSphere that we can use to ensure that Apache is delegating requests on ports 80 and 443 for that application context. Open http://localhost/PlantsByWebSphere/ and https://localhost/PlantsByWebSphere/ in your browser.
    Figure 2. Successful Web server plug-in installation.
    Successful Web server plug-in installation

PHP

Now, confirm that PHP is also enabled for Apache:

  1. Create a file in /opt/local/apache/htdocs/ named test.php and enter the following code:

    Listing 19. Confirm PHP
    <?php phpinfo(); ?>
  2. Access this file on ports 80 and 443 with the following URLs: http://localhost/test.php and https://localhost/test.php
    Figure 3. Successful PHP installation.
    Successful PHP installation
  3. You need to make a few minor changes to the php.ini file in order to get BLOB data from DB2 correctly through the ODBC interface of PHP. These fixes are documented in the article, Application Development Experiences with PHP and IBM DB2 Universal Database Version 8. If you don't yet have a /opt/local/php/lib/php.ini file, copy it over from the src directory.

    Listing 20. Create php.ini if it doesn't exist
    cp ~/src/php-5.0.4/php.ini-recommended /opt/local/php/lib/php.ini

    In php.ini, make sure that the following values are set for these two keys.

    Listing 21. New php.ini values
    ; Handling of LONG fields.  Returns number of bytes to variables.  0 means
    ; passthru.
    odbc.defaultlrl = 1M
    
    ; Handling of binary data.  0 means passthru, 1 return as is, 2 convert to char.
    ; See the documentation on odbc_binmode and odbc_longreadlen for an explanation
    ; of uodbc.defaultlrl and uodbc.defaultbinmode
    odbc.defaultbinmode = 1
  4. Next, install the PHP Extension and Application Repository (PEAR) Database Abstraction Layer (DB), which is a package that provides a common interface to PHP's database-specific functions. This provides a common API for data access similar in spirit to JDBC.

    Listing 22. Download and install PEAR DB
    /opt/local/php/bin/pear install DB
  5. Finally, restart Apache.

    Listing 23. Restart Apache
    /opt/local/apache/bin/apachectl stop
    /opt/local/apache/bin/apachectl startssl

Operating system users

Our application uses two different users to access the database:

  • the content management system user
  • the public site user.

You want to provide different privilege levels for both types of users. Create two minimal operating system users for authentication and table-level DB2 privileges: cms_usr and site_usr. Set their initial passwords as well. For the purposes of this article, each password is the same as the user name.

Listing 24. Create new users and set their passwords
useradd -c "Catabase DB2 Site User" -s /bin/false site_usr
useradd -c "Catabase DB2 CMS User" -s /bin/false cms_usr
passwd site_usr
passwd cms_usr

Configure the middleware for the Catabase application

While the Catabase Web application is comprised of two separate components, they share the same database. The content management system authorization is enabled to INSERT, UPDATE, and DELETE, whereas the public site user is only given SELECT privileges.

Create the database

  1. The Catabase data model structure is shown in Figure 4. The sample code provides the Data Definition Language (DDL) and Integration Exchange Format (IXF) files which make up the structure. You will still need to create a database named CATABASE to populate first.
    Figure 4. The Catabase data model
    The Catabase data model
    Listing 25. Create the database
    db2 => CREATE DATABASE CATABASE
  2. Now, create our tables by importing the DDL from the catabase.ddl file found in the download code sample. The DDL also contains the GRANT statements for our two database users. You will need to run this command from a regular shell prompt, not the interactive Command Line Processor.

    Listing 26. Create the tables
    # db2 -tf catabase.ddl
  3. Next, populate the tables with initial data using the IXFs provided in the download file.

    Listing 27. Import the data
    db2 => import from BREEDS.ixf of ixf insert into BREEDS
    db2 => import from COLORS.ixf of ixf insert into COLORS
    db2 => import from NOTE_TYPES.ixf of ixf insert into NOTE_TYPES
    db2 => import from ROLES.ixf of ixf insert into ROLES
    db2 => import from STATUSES.ixf of ixf insert into STATUSES
    db2 => import from PHOTOS.ixf of ixf insert into PHOTOS
    db2 => import from CATS.ixf of ixf insert into CATS
    db2 => import from HUMANS.ixf of ixf insert into HUMANS
    db2 => import from ADOPTIONS.ixf of ixf insert into ADOPTIONS
    db2 => import from NOTES.ixf of ixf insert into NOTES
    db2 => import from HUMAN_ROLE.ixf of ixf insert into HUMAN_ROLE
    db2 => import from CAT_PHOTO.ixf of ixf insert into CAT_PHOTO
    db2 => import from CAT_COLOR.ixf of ixf insert into CAT_COLOR
    db2 => import from CAT_BREED.ixf of ixf insert into CAT_BREED
  4. Make a final optimization for DB2, which is described in the article, Develop IBM Cloudscape and DB2 Universal Database applications with PHP. These commands will improve the performance of our PHP application queries.

    Listing 28. Optimize DB2 queries for PHP
    db2 => UPDATE CLI CFG FOR SECTION CATABASE USING LONGCOMPAT 0
    db2 => UPDATE CLI CFG FOR SECTION CATABASE USING PATCH2 6

Create the data source in the administrative console

  1. WebSphere Application Server can now be configured to connect to the application database. Create two login aliases that map to the operating system users. In the WebSphere Application Server administrative console, we need to create Java 2 Connector security users:
    • Select Security => JAAS Configuration => J2C Authentication Data.
    • Select New and enter cms_usr as the Alias and User ID, along with the Password that you established earlier, then OK.
    Repeat these steps for site_usr and then Save your changes.
  2. Next, create a new JDBC Provider:
    • Select Resources => JDBC Providers, then New.
    • Select DB2 Universal JDBC Driver Provider from the JDBC Providers list and then OK.
    • Accept the defaults on the following page, making sure that the entries below are in the Classpath box:
      • ${DB2UNIVERSAL_JDBC_DRIVER_PATH}/db2jcc.jar
      • ${UNIVERSAL_JDBC_DRIVER_PATH}/db2jcc_license_cu.jar
      • ${DB2UNIVERSAL_JDBC_DRIVER_PATH}/db2jcc_license_cisuz.jar
  3. Define one of the variables that was used in the classpath entry above. Select Environment => Manage WebSphere Variables. Make sure that the two variables below are set to the DB2 installation root:
    • DB2UNIVERSAL_JDBC_DRIVER_PATH = /opt/IBM/db2/V8.1/java
    • UNIVERSAL_JDBC_DRIVER_PATH = /opt/IBM/db2/V8.1/java
  4. Next, create two data sources for the driver, one for each DB2 user. In the Additional Properties box, select JDBC Providers => DB2 Universal JDBC Driver Provider => Data Sources. Select New and enter the following values for this datasource:
    • Name: Catabase CMS Data Source
    • JNDI Name: jdbc/catabasecms
    • Component-managed Authentication Alias: cms_usr
  5. Repeat step 4 for the second data source with these values:
    • Name: Catabase Site Data Source
    • JNDI Name: jdbc/catabasesite
    • Component-managed Authentication Alias: site_usr
  6. For both new data sources, select their names in the Data Sources window, then select Custom Properties in the Additional Properties box. In the resulting window, set these values for both data sources:
    • driverType: 4
    • databaseName: CATABASE
    • serverName: 127.0.0.1
    • portNumber: 50001
  7. Save your changes and return to the Data Sources pane and click Test Connection. You should see a message similar to Figure 5.
    Figure 5. The Catabase data sources
    The Catabase data sources

Install the Catabase application

The content management tool

Our next step is deploying the Catabase Enterprise ARchive (EAR) to WebSphere Application Server.

  1. From the WebSphere administrative console, select Applications => Enterprise Applications.
  2. Click the Install button, then Browse... to upload the CatabaseEAR.ear file from the download code sample.
  3. For generate default bindings and mappings, select Next.
  4. At Step 1: Provide options to perform the installation, select Next.
  5. At Step 2: Map resource references to resources, select jdbc/catabasecms.
  6. At Step 3: Map virtual hosts for Web modules, select Next.
  7. At Step 4: Map modules to application servers, select Next.
  8. At Step 5: Summary, select Finish, then Save to Master Configuration.
  9. Select Applications => Enterprise Applications again.
  10. Check the box next to CatabaseEAR and click the Start button.
  11. Select Environment => Update Web Server Plugin and click OK.
  12. To verify the installation, open https://<localhost>/admin/ and log in with the default name of a user with Administrator rights; krook@example.com with a password of DAN (Figure 6).
    Figure 6. The cat entry form.
    The cat entry form

The PHP sample code

The public site PHP 5 application reuses some of the same conceptual objects as the Struts application, such as Cat and Human. It also provides a demonstration of some new PHP 5 features. The book Upgrading to PHP 5 in Resources has indepth descriptions of these improvements:

  • Encapsulation of object members through the magic_set and _get functions.
  • Private constructors for each manager singleton.
  • The object-oriented version of DOM transforms Cat objects to XML for the RSS feed.
  • The _toString method provides a summary of object state when using echo.

The public Web site

We simply need to install the contents of the htdocs directory into the Apache server root /opt/local/apache/htdocs to install the Catabase public Web site.

Figure 7 shows the directory layout for the PHP application. Because application development in PHP is not as structured as the J2EE standard or Struts frameworks, the design has leeway for customization.

Figure 7. The site directory structure
The site directory structure

To install, you can extract the PHP application from the download file. Copy the contents of the htdocs folder to /opt/local/apache/htdocs. To verify the installation, open your browser to http://<localhost>/, and you should see output similar to that shown in Figure 8.

Figure 8. The public site.
The public site

Tying the applications together

To confirm that your installation of the Catabase application has been configured correctly, use the Add and Modify links in the content management tool to work with the sample cats included, or add your own. Then, open the public site to display your changes. The Catabase Web site landing page will display the last three featured animals, while the Catalog page in the Adopt cats section will show them all. You can also search the entries in the Site tools section.


Conclusion

This article showed how Apache, MySQL, and PHP technologies, and IBM middleware fit the roles of the common three-tiered Web application model. We also saw how individual software packages from either group can be swapped into each role independently of each other. Finally, we have seen that you can even combine traditionally competing packages at the same tier to fit a business need, as in the case of the Catabase, which supported two different audiences through a common Web server to a set of data. Hopefully, this demonstration and the steps provided have inspired you to develop new and innovative Web applications with the tools offered by both IBM and the open source community.


Acknowledgments

I would like to thank Catherine Fugarino for her support and Scott Rademaker for reviewing this article. I also want to acknowledge Carlos Hoyos, Larry Lin, Albert James, Martina James, Doug Weatherbee, Tim Gales, and Chris Snyder for their helpful input.


Download

DescriptionNameSize
Catabase Web applicationcatabase.zip  ( HTTP | FTP )2.4 MB

Resources

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into WebSphere on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere, Open source, Information Management
ArticleID=83200
ArticleTitle=IBM WebSphere Developer Technical Journal: Pair J2EE with PHP to implement a common Web application infrastructure
publish-date=04272005