×

Uh-oh, it looks like your Internet Explorer is out of date.

For a better shopping experience, please upgrade now.

The IBM i Programmer's Guide to PHP
     

The IBM i Programmer's Guide to PHP

by Jeff Olen
 

See All Formats & Editions

The PHP programming language is thoroughly examined in this guide for programmers looking to transfer their skills from the interface of a green-screen environment to using web-enabled technologies. As developers are experiencing more demand for such technologies, PHP programming language has become the language of choice for many developers who are required to

Overview

The PHP programming language is thoroughly examined in this guide for programmers looking to transfer their skills from the interface of a green-screen environment to using web-enabled technologies. As developers are experiencing more demand for such technologies, PHP programming language has become the language of choice for many developers who are required to obtain more web-friendly skills. Commonly used features are discussed and look beyond the PHP language itself to help programmers begin building highly interactive web-based applications. PHP’s flexible and forgiving programming style was designed to be the ideal environment for ease of building both simple and complex web-based applications in the most effective manner possible while still giving programmers the control they need. Sample topics include how to build basic PHP applications, how to access local and remote resources, how to access System i DB2 database tables from PHP, how to install and access MySQL databases on the System I, the basics of internet security, structuring a PHP application, and accessing external data sources.

Product Details

ISBN-13:
9781583476147
Publisher:
Mc Press
Publication date:
03/01/2012
Sold by:
Barnes & Noble
Format:
NOOK Book
Pages:
450
File size:
8 MB

Read an Excerpt

The IBM i Programmer's Guide to PHP


By Jeff Olen, Kevin Schroeder

MC Press

Copyright © 2009 Jeff Olen and Kevin Schroeder
All rights reserved.
ISBN: 978-1-58347-614-7



CHAPTER 1

Getting Started


PHP is the successor of a product called PHP/FI, which was written by Rasmus Lerdorf in 1995. PHP/FI, which stood for Personal Home Page/ Forms Interpreter, was a set of scripts used to monitor and maintain Web pages. The PHP language as we know it today was created in 1997 by Andi Gutmans and Zeev Suraski and was a complete rewrite of the original PHP/FI 2.0. The version of PHP eventually released late in 1998 was called PHP 3.0. (Those interested in the historical releases of PHP can find them at http://museum.pdh.net) The name "PHP" is a recursive acronym that stands for "PHP: Hypertext Preprocessor."

Today's PHP has gone through several rounds of improvements to become a robust and powerful server-side tool for developing dynamic Web content. However, for those of us who have spent our careers working on the IBM System i and its many predecessors, there has been little to interest us about PHP — that is, until recently. Now, Zend Technologies has partnered with IBM to develop a version of the Zend Core for i5/OS. Zend Core is a high- quality (read "supported") version of PHP 5. As of this writing, the current version of Zend Core for i5/OS, Version 2.6, provides the basis for developing PHP-based applications that run natively on the System i. Perhaps best of all for System i developers, two PHP extensions, IBM_DB2 and PDO_IBM, enable us to develop applications that access IBM DB2 database files.

So, there now exists a simple (relatively speaking) tool we can use to develop enterprise-level Web content on the System i. What are we waiting for? Um ... good question. Let's get started.


Static vs. Dynamic Content

A static Web page or static Hypertext Markup Language (HTML) undergoes no changes or tailoring before being displayed to the ultimate end user. We can liken this type of interface to that of a DDS display file that contains nothing but literals and thus always displays the same thing. Another way to think of static HTML is as "hard-coded" HTML.

Although there's nothing wrong with static content or static HTML, your ability to create complex and interesting Web content is severely limited in this context. For example, suppose you'd like to display the current time and a simple personalized greeting message for each user. You cannot do these things with static HTML, although static HTML can have dynamic elements through the use of a client-side scripting language, such as JavaScript.

Dynamic content is content that responds to user interaction. To some degree, every Web site is dynamic, in that it responds to a user's actions and because HTTP is a request/response protocol. But for the purposes of our discussion, dynamic content refers to content that can react and change based on some kind of programmatic expression either on the server side or on the client side. And because we're talking PHP, we're talking server side. What this means is that you use PHP to generate some kind of content on a Web server. Although the first type of content that might come to your mind is HTML, that is only one type of many. You can render HTML, images, Portable Document Format (PDF) documents, JavaScript Object Notation (JSON), Extensible Markup Language (XML), and a host of different types of content using PHP.

You create dynamic content in different ways depending on which tools you are using. One important difference has to do with where the scripting programs are interpreted: on the local PC or on the Web server. These two distinctions are commonly referred to as client-side scripting and server-side scripting.


Client-side vs. Server-side

JavaScript is one example of a client-side scripting language with which you're probably familiar. JavaScript is usually interpreted on the client, although some Web servers can interpret it as a server-side language. In basic terms, this means that the JavaScript source code is transmitted to the client and then executed on the client machine. This approach has several drawbacks, not the least of which is that it can be slow, especially if you lack a high-speed network connection. Another drawback is that the source code is transmitted to the client. This exposure means that nothing confidential or business-related should be included in any way in the source code.

In server-side scripting, the script is executed on the server machine. In this case, the execution speed is limited not by the speed of your connection (at least not as much) but rather by the speed of the host machine. Also, because the source code always remains on the server, it can contain confidential information and business rules (unless your Web server or application has some kind of vulnerability).


What You'll Need

To follow along with the examples and exercises presented here and get the most from the information in this book, you should have the Zend Core for i5/OS installed on your System i. You'll also need one of the integrated development environments (IDEs) for PHP; we use the Zend Studio. Other IDEs are available, and you're free to use whichever one you feel most comfortable with. To be honest, there is nothing to stop you from loading PHP on your local machine and running your own Apache Web server. This setup is perfectly fine for most of the exercises that relate to PHP in general. However, later on we'll address topics that relate specifically to developing applications on and for the System i. At that time, you'll need access to an iSeries with PHP installed on it. The good news is that Zend Core and Zend Studio for i5/OS are both available for free; you can download them from the Zend Web site, http://www.zend.com.

Both products come with PDF installation documents that are fairly straightforward and easy to follow. This documentation lists several IBM licensed programs as prerequisites. These programs are all included on your i5/OS installation media, but, as optional components, they may not have been preloaded on your machine. If the required programs are not loaded, you can either load them from your installation media or contact your IBM SE and order them. Ordering the media should be free as long as you are on software support.

To stay focused on getting you coding PHP as quickly as possible, we're going to forego providing detailed install instructions here. The installation guide includes reasonably good troubleshooting tips in case you run into problems. The Zend Support Forums (http://www.zend.com/forums) provide further information, and you can find good answers to your questions there.

Two other tools may be useful for you, although neither is required:

Smarty: This fairly robust templating engine is handy for quickly creating uniform-looking pages. However, it adds another layer of processing between PHP and the final HTML output. Smarty is available at http://www.smarty.net.

Firebug: This on-the-fly debugger for Cascading Style Sheets (CSS), HTML, and JavaScript comes in handy, especially when you're trying to debug generated HTML. It is available only for Firefox, though, so if you're using Internet Explorer, you're out of luck. Firebug is available at http://www.getfirebug.com.


Testing Your Zend Core Install

Once you've installed the Zend Core for i5/OS, there are a few things you can do to verify that the installation was successful.

First, access the Zend Core menu from the green screen by issuing the following command:

GO ZENDCORE/ZCMENU

This command should bring you to a menu that looks like the one shown in Figure 1.1. If you see this menu, that's a good indication that the installation was completed successfully.

Next, try to start the Zend subsystems and the Apache servers. To do so, on the Zend Core menu, select option 5 (Service Management menu) to display the menu shown in Figure 1.2.

Start the Zend subsystem first by selecting option 1 (Start Zend Core Subsystem). If you receive a message that says "Zend Core Subsystem already active" or "Zend Core subsystem started," you're okay. Any other message may indicate an installation problem; refer to the installation guides to troubleshoot.

Next, choose option 4 (Start Apache server instances) to start the Apache servers. You should see a message that reads "Zend Core Apache instance started."

If you're able to complete these steps, your installation verification is just about finished. The last step is to make sure the Zend Core administration interface is available. To do this, open your Web browser, and enter the following URL:

http://server_name:89/ZendCore

Replace server_name with the name or IP address of your i5/OS machine. For example, the IP address of our machine is 192.168.253.31, so we would use this URL:

http://192.168.253.31:89/ZendCore

Once you type the URL and press Enter, you should see the Zend Core administration login, shown in Figure 1.3.

We will address the Zend Core administration menu and the options available to you there a bit later. For now, it is enough to verify that you can display the login menu.


PHP Syntax

Syntax is critical in nearly every programming language, and PHP is no exception. So before we launch into writing your first PHP script, let's go over some basic syntax. With this quick background, you'll have a far greater chance of writing understandable code.


Variable Names

PHP variable names always start with a dollar sign ($). Variable names are case- sensitive and can contain only alphanumeric characters and underscores. In addition, the character following the $ must be either a letter or an underscore. For those of you acquainted with C/C++, this naming style should be familiar. For us RPG developers, having case-sensitive variable names can be a little hard to get used to. It can make debugging a little tougher, too, but we'll get to that topic later. Here are some valid PHP names:

$counter
$oldInvoiceDate
$last_Billed_4

Table 1.1 lists some invalid PHP names along with notations as to why they are invalid.


Data Types

In PHP, the type of a variable is decided at runtime based on the context in which the variable is used. PHP uses four basic data types, two compound data types, and two special data types.

• Basic data types:

" String — Text of any sort or other data that is treated as text (letters or numbers in quotation marks)

» Integer — Any whole number

» Float — Any decimal number

» Boolean — TRUE or FALSE values (similar to indicators in RPG but more useful)

• Compound data types:

» Array

» Object

• Special data types:

» Null

» Resource


PHP is a weakly typed language, which means that a variable in PHP need not have a predefined type. Instead, the variable's type is determined by the type of data placed into it, and its value is determined by the context in which it is operated on. This aspect of PHP differs greatly from Java and RPG, both of which are strongly typed languages. A strongly typed language requires variables to be explicitly given a type, and only a specific type of data can be placed into each variable.

In addition to being weakly typed, PHP variables can have their type changed at runtime. The following code uses several methods to change the type of a variable a runtime.

// initial value is integer, so variable is integer type
$invoice = 10;

//manually set the type to double
settype ($invoice, 'double');

//a string value placed in the variable
//will change it to a string type
$invoice = 'Ivoice# 10';

Another way to change the type of a variable at runtime is through a process called casting. Casting differs from the preceding examples in that it returns a value of the specified type but does not change the type of the variable itself. The following example illustrates a cast.

// initial value is integer, so variable is integer type
$invoice = 10;

//cast to double
echo 'invoie number is '.(double) $invoice;
echo '$invoice is type double: '.(is_double($invoice)?'true': 'false');


Consider the following variable definitions:

$intNumber = 4; // $intNumber is type integer
$floatNumber = 3.14159; // $floatNumber is type float
$strName - 'Jeff Olen'; // $strName is type string
$boolResult = TRUE; // $boolResult is type Boolean

Starting with the variables as defined here, what are the results of the following code?

$boolResult = 'Type will change';
$boolResult = $netSalary * 0.25;
$boolResult = (integer) 3.14159;

After the first line of code is executed, the $boolResult variable, initially a Boolean type, is a string type. After the second statement is executed, $boolResult is a float. And after the third line, $boolResult is an integer type containing the value 3 (the decimal places are truncated during the casting process).

Weakly typed variables can be a bit difficult to get used to if you're accustomed to working with a strongly typed language such as RPG. But they can be useful, too, as we'll discuss later.

The last line of sample code above uses a technique known as type casting. This technique lets you as the developer specifically determine the data type of an expression. For now, you just need to be aware that this capability exists; we'll go into a more comprehensive description of how to use it later.


Arrays

Arrays are considered compound data types because they can contain different types of data. For example, an array could contain the following entries:

$array1[0] = 3.14159; // element 0 type is float
$array1[1] = 'Jeff Olen'; // element 1 type is string
$array1[2] = 30; // element 2 type is integer

Here, each array element contains a different type of data and is therefore assigned a different type. Again, this differs from what we are used to with RPG, which permits only a single data type for all elements in an array.

PHP's compound and special data types, especially arrays, are important and are the subject of an entire chapter later on. For now, the preceding basics are enough to get you started working with PHP data types.


Comments

You can write PHP comments n several different ways. A double slash (//) or a number sign (#) designates a single-line comment:

// this is a commnet

$test = TRUE; // this is a comment
$test = FALSE; # and so is this

Single-line comments can also be written using the delimiters /* and */, similar to the way these delimiters function in CL:

/* This is a comment */


The same delimiters also let you compose multi-line comments:

/* This is a multi-line comment. The delimiters show where the comment begins and ends. */

You can also include PHPDoc comments in your code. The PHPDocumentor tool serves a similar purpose to Javadoc in that it helps to document your code. PHPDoc uses the same syntax as Javadoc:

/**
/* This is a PHPDoc comment - used for classes & functions.
/* PHPDoc comments are a very powerful way to document your
/* code. There's more about them in Appendix A.
/* @param Integer - Customer number
/* @return String - Customer number
*/

We won't go into a long dissertation about commenting your code, but, as you know, good comments make code much easier to read and understand later on. Once we really get into using the PHPDoc comments, you'll see how commented code can be truly self-documenting. PHPDoc is also unique from the other comment types in that the Zend Engine retains the PHPDoc during execution. You can then use the PHPDoc comments with the PHP Reflection API. For more information about PHPDoc and Reflection, visit the Reflection page of the online PHP manual at http://us.php.net/reflection.


Single Quotes vs. Double Quotes

Single quotation marks (') and double quotation marks (") are both valid in PHP, but they each function differently. PHP treats a string enclosed in single quotation marks as a literal, as in the following code:

$literalValue = 'The name of the book is "Oliver Twist"
and it was published in 1864.';
$literalValue = 'The value of $invoice_num is:';

In both of these examples, the value of $literalValue will be exactly the string between the single quotes.

Double quotation marks, on the other hand, let you place a variable within a string. This option can be very useful, as the next example demonstrates.

$invTermDays = 15;
$invoiceComment = "Net due in $invTermDays days.";

Here, the value of $invoiceComment will be "Net due in 15 days." This method of embedding a variable in a string is called variable interpolation. You can code this type of interpolation as we've done in the preceding code, but the preferred method — and the way you will see it done from now on in our code examples — is as follows:

$invoiceComment = "Net due in {$invTermDays} dasy.";

As you can see, we've surrounded the variable name with curly braces ({}). The reason behind this style preference may not be immediately apparent. Consider this example:

$day = 'Monday';
echo "There are 5 $days this month';

You might expect the output of this code to be "There are 5 Mondays this month", but you would be wrong. The PHP interpreter looks for a variable called $days, not $day. By sticking to the preferred method of enclosing interpolated variables in braces, you can avoid this and similar issues:

$day = 'Monday';
echo "There are 5 {$day}s this month';


Escape Sequences

At times, you may need to embed a single quote (apostrophe), a dollar sign, or another symbol inside a literal. To do so, you use an escape sequence. All PHP escape sequences begin with the backslash (\) character. Table 1.2 lists some of the special-character escape sequences available in PHP.

If an escape sequence appears in between single quotes, the PHP interpreter will not expand it. The exception to this rule is the single quote itself, as the first example below demonstrates.

$val = 'fooled ya, ';

printf('This is a \'test\' ');
printf('This is another test $val');
printf("And yet another test $val");
printf("one last \$2.00 test");

The preceding code produces the following output:

This is a 'test'
This is another test $val
And yet another test fooled ya.
one last $2.00 test

Although escape sequences may seem handy, you can and should avoid their use. This is possible in several ways. The simplest way is to use the appropriate quotation marks (single or double), depending on the need. By simply changing a few of the quotes, the following code eliminates the need for the escape sequences.

$val = 'fooled ya, ';

printf('This is a 'test'");
printf('This is another test $val');
printf("And yet another test $val");
printf("one last \$2.00 test");


Odds and Ends

A few last items related to PHP syntax:

• Each PHP statement ends with a semicolon (;).

• Every PHP script starts with the opening tag <?php or the short tag <? (more about short tags later).

• The closing tag ?> is required only if additional HTML tags follow the last line of PHP code.


Your First PHP Script

With a firm grasp of the basic syntax and structure of PHP, you're ready to write your first script. We've never been fans of "Hello World" programs, but one is almost expected in a book like this. With that said, open Zend Studio, select File from the drop-down menus available across the top of the screen, and select New File to create a blank document on which to work. Then key in the following code:

<?php
echo "Hello World!";
?>


(Continues...)

Excerpted from The IBM i Programmer's Guide to PHP by Jeff Olen, Kevin Schroeder. Copyright © 2009 Jeff Olen and Kevin Schroeder. Excerpted by permission of MC Press.
All rights reserved. No part of this excerpt may be reproduced or reprinted without permission in writing from the publisher.
Excerpts are provided by Dial-A-Book Inc. solely for the personal use of visitors to this web site.

Meet the Author

Jeff Olen is the owner and founder of Olen Business Consulting Inc. and has developed PHP applications on the System i for a wide variety of clients. In addition to extensive development experience with RPG, he has also developed applications using C, C++, Javascript, HTML, PHP and MySQL. He lives in Orange, California. Kevin Schroeder is a technical consultant for Zend Technologies and has developed production software using a wide variety of languages including PHP, Java, Javascript, HTML, SQL, Perl, Visual Basic, ASP, and C. He lives in Frisco, Texas. Jeff Olen is the owner and founder of Olen Business Consulting Inc. and has developed PHP applications on the System i for a wide variety of clients. In addition to extensive development experience with RPG, he has also developed applications using C, C++, Javascript, HTML, PHP and MySQL. He lives in Orange, California. Kevin Schroeder is a technical consultant for Zend Technologies and has developed production software using a wide variety of languages including PHP, Java, Javascript, HTML, SQL, Perl, Visual Basic, ASP, and C. He lives in Frisco, Texas.

Customer Reviews

Average Review:

Post to your social network

     

Most Helpful Customer Reviews

See all customer reviews