24
Wed, Apr
0 New Articles

TechTip: Start Using PHP on the iSeries...NOW! Part III

Web Languages
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

In Part I of this series, I showed how to install PHP on your iSeries and make sure it was functioning. In Part II, I walked though developing a simple database-listing script. Now I'm going to give you the Holy Grail of leveraging your existing code. I'll show you how to CALL your existing iSeries programs and service program functions from PHP. Well, OK, it's not actually the Holy Grail, but it's still a really good way to leverage existing code.

To start, you'll need to have the Zend Core for i5/OS installed and configured. If you don't have it already, you can download it for free. The installation instructions are also available on the Zend Web site. The next item is the Toolkit_Classes.php script, and it's installed with the Zend Core. It should be on the IFS in the /www/zendcore/htdocs/i5Toolkit_librarydirectory. You can either leave it in that directory and use a qualified Include statement (see below) or copy it into the directory where your other source code resides and use an unqualified Include statement, as I have in the sample. It should be noted that you do not have to use the Toolkit_Classes.php classes when you write your own scripts. Zend simply provides it as an example of how you can implement the base i5 functions included in the Zend Core for i5/OS product. Also, included is a demo script called “demo_for_toolkit_classes.php” that demonstrates other i5 functions. I used Toolkit_Classes.php it in our sample for the sake of simplicity.

Qualified Include:

require_once("/www/zendcore/htdocs/i5Toolkit_library/Toolkit_Classes.php");

I've created a sample script that calls a program with two parameters. The source for the sample is shown below with my descriptions, and a working version can be downloaded here.


include_once('Toolkit_classes.php');

// Functions
// Error function – display i5 call errors 
function throw_error($errDesc) {
echo "Error Description: ".$errDesc."
";

echo "Error Number: ".i5_errno()."
";

echo "Error Message: ".i5_errormsg()."
";

}

// Main script
// $USER and $PASSWORD must be a valid iSeries user profile login
$USER     = "user";
$PASSWORD = "password";

// connect to the iSeries  
try {  
$conn = new i5_Connection('127.0.0.1', $USER, $PASSWORD); Step 1 - create connection  object and connect to  the iSeries.
$conn->connect();
} catch (Exception $e) {
echo "Failure to connect";
echo $e->getMessage();
die();
}


// create parameter descriptions Step 2 – create the descriptions for the parms
$desc = new i5_Description();
$desc->I5_TYPE_PACKED('Parm1','3.0', I5_INOUT);
$desc->I5_TYPE_PACKED('Parm2', '3.0', I5_INOUT);

// create program object
$prog = new i5_Program('JEFFO','TESTAPI', $desc, $conn); Step 3 - create the program object.

// set the parameter values to pass to the program
$prog->__set('Parm1', 12 );Step 4 – load the parm values to pass into the program
$prog->__set('Parm2', 0 );

// call the program

$ret = $prog->call(); Step 5 – call the program
if (!$ret) {
    throw_error("i5_program_call");
    exit();
}

// check for errors. If no error then display the result values
if(is_null($prog->LastErr)){ Step 6 – check for errors calling the program
echo 'result Parm1:'.$prog->__get('Parm1').'
';

echo 'result Parm2:'.$prog->__get('Parm2').'
';

}
// if error found then display error details
else
{
    throw_error("Call Failed");
}
?>

This relatively simple example calls program TESTAPI in library JEFFO. The first thing you must do to prepare to run a native iSeries program is create a i5_Connection object and connect to the iSeries using a valid user profile and password. This is similar to Java code you have probably seen in the past and serves the same purpose.

try {  
$conn = new i5_Connection('127.0.0.1', $USER, $PASSWORD); Step 1 - create connection  object.
$conn->connect(); attempt to actually connect
} catch (Exception $e) { handle connection errors
echo "Failure to connect";
echo $e->getMessage();
die();
}

Next, you need to create the i5_Description object to describe the parameter values that you will be passing and receiving data in. You can think of this step as the equivalent of prototyping for a CALLP. The processing on the iSeries side of things needs to know the type, size, and usage of each parameter, and the i5_Description object is how this is accomplished. In the example above, both parameters are three-digit packed decimal with no decimal places. Below are some examples of how to define other variable types:

Always create the $desc object first:

$desc = new i5_Description();

Then, add as many parameters as you need:

// 10 Character – input/output
$desc->I5_TYPE_CHAR('Parm1','10', I5_INOUT);

// 9,4 zoned decimal  input/output
$desc->I5_TYPE_ZONED('Parm2','9.4', I5_INOUT); 

// 3,0 packed decimal  input/output
$desc->I5_TYPE_PACKED('Parm3','3.0', I5_INOUT); 

// 1 byte character input/output 
// (use for an indicator parm or return value)
$desc->I5_TYPE_CHAR('Parm4','1', I5_INOUT); 

The Toolkit_Classes.php and the Zend Core user guide have definitions for I5_TYPE_FLOAT, I5_TYPE_INT and I5_TYPE_LONG, and the support for these types will be available in an upcoming release. However, if you contact Zend support, they will send you a patch that will enable these data types in the current release. On a side note, the I5_TYPE_CHAR used with a length of one ('1'), as shown above, will function correctly for indicator-type parameters.

Once the parameter definitions are created, you're ready to create the i5_Program object. This time, you'll use both of the objects you already created: the i5_Description object and the i5_Connection object. In addition to those parameters, the i5_Program class requires the library name and program name of the program you're going to call. Yes, you can use *LIBL as the library. The library list functions just like you would hope. The list used when calling a program is by default the library list defined for the job description of the user profile that you used when you established the connection to the iSeries.

// create program object
$prog = new i5_Program('JEFFO','TESTAPI', $desc, $conn); Step 3 - create the program object.

After the i5_Program object is created, you can use the __SET method to set the values of the parameters you want to pass into the program. In the sample script, I set the values of my two numeric parameters to 12 and 0.

$prog->__set('Parm1', 12 ); Step 4 – load the parm values to pass into the program
$prog->__set('Parm2', 0 );

Now you can call the program.

// call the program
$ret = $prog->call(); Step 5 - call the program
if (!$ret) {
    throw_error("i5_program_call");
    exit();
}

The return value $ret will be false (0) if the program call fails. The values of the parameters returned after the program completes are returned in a separate structure. The i5_Program class takes care of this for you and allows you to access the returned values by using the __GET method. Take a look at the Toolkit_Classes.php if you are interested in how this actually takes place. It's an exercise that's worth the effort.

The only drawback I have come across with calling the native programs this way is in how the service program functions are supported. You can call a service program function the same way you call a program. The example below creates an i5_Program object to call the TESTFUNC procedure in the TESTAPI3 service program.

// create program object
$prog = new i5_Program('JEFFO','TESTAPI3(TESTFUNC)', $desc, $conn);

The issue is that some service functions return values. By that, I mean they use the "Return someValue;" syntax. Currently, there's no way to receive the values returned using the RETURN opcode. So that's a little limiting when you're using service programs.

There's much more functionality available regarding calling programs and commands from PHP, and I encourage you to experiment with it. The topic for Part IV (if there is to be a Part IV) has not yet been decided upon. So let me hear from you. Tell me what you'd like to know more about.

Jeff Olen is the owner of Olen Business Consulting, Inc., an iSeries development services company based in Orange, California. When he's not busy writing code or writing articles, you can find him jumping out of perfectly good airplanes (a.k.a. skydiving). To find out more about Jeff or Olen Business Consulting, Inc., go to www.olen-inc.com or email Jeff at This email address is being protected from spambots. You need JavaScript enabled to view it..

Jeff Olen

Jeff Olen is a super-spy now but keeps his cover identity intact by working for video game studios on the East Coast. So when he’s not out killing members of ISIS or rescuing refugees, you can find him playing Wolfenstein II or testing the new Fallout 76 releases at his beach house in Costa Rica. In any case, he can’t be reached. You can email his cat at This email address is being protected from spambots. You need JavaScript enabled to view it.. She will pass on your message…if she feels like it.


MC Press books written by Jeff Olen available now on the MC Press Bookstore.

The IBM i Programmer’s Guide to PHP The IBM i Programmer’s Guide to PHP
Get the scoop on how PHP can—and should—be deployed on IBM systems.
List Price $79.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: