Tải bản đầy đủ (.pdf) (72 trang)

Tài liệu PERFORMANCE MANAGEMENT OPPORTUNITIES doc

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.39 MB, 72 trang )

DECEMBER 2002 - Volume I - Issue 1
The Magazine For PHP Professionals
php|architect
Zeev Suraski - Brad YoungZeev Suraski - Brad Young
P
ERFORMANCE
M
ANAGEMENT
O
PPORTUNITIES
Reviewed for you:
Zend Performance Suite
Davor's PHP Editor
Plus:
SNMP Management With PHP
PHP nCurses Shell Programming
Writing a Webmail System
Distill PDFs For Free With PHP
Create a DB Abstraction Layer
In Colaboration with
SUBSCRIBE AND
WIN!
Comparing PHP With the Industry at Large
Technologies Ltd.
Visit
www.zend.com
for evaluation version and ROI calculator
Zend Performance Suite
Reliable Performance Management for PHP
Serve More.
With Less.


The designers of PHP offer you the full spectrum of PHP solutionsThe designers of PHP offer you the full spectrum of PHP solutions
IINNDDEEXX
Departments
4 | Editorial rants
5 | New Stuff
6 | PHP-Win
A Look at Davor’s
PHP Editor
61 | Product Review
Zend Performance Suite
Version 2.5
65 | Tips & Tricks
by John W. Holmes
70 | For Your Reading
Pleasure
Book Reviews by the
php|a team
72 | Exit(0);
A War With No Enemies
TABLE OF CONTENTS
December 2002 · PHP Architect · www.phparch.com
3
php|architect
Features
9 | Performance Management
Opportunities
by Zeev Suraski and Brad Young
14 | Curses!
Writing Cool Shell Applications
With PHP

by Marco Tabini
25 | SNMP Management
With PHP
by Harrie Hazewinkel
34 | A Concrete Look at
Database Abstraction Layers
by Maxim Maletsky
41 | Creating A Visual Catalogue
System with PHP and IE
by Davor Pleskina
49 | Writing a Web-based
PDF Converter
by Marco Tabini
55 | Directing Mail with qmail’s
Maildirs
by Jonathan Sharp
EEDDIITTOORRIIAALL RRAANNTTSS
EDITORIAL
December 2002 · PHP Architect · www.phparch.com
4
php|architect
Volume I - Issue 1
December, 2002
Publisher
Marco Tabini
Editors
Arbi Arzoumani
Marco Tabini
Graphics & Layout
Arbi Arzoumani

Administration
Emanuela Corso
Authors
Arbi Arzoumani, Harrie Hazelwinkel,
John W. Holmes, Maxim Maletsky,
Davor Pleskina, Jonathan Sharp,
Zeev Suraski, Marco Tabini, Brad
Young
php|architect (ISSN 1705-1142) is published
twelve times a year by Marco Tabini & Associates,
Inc., P.O. Box. 3342, Markham, ON L3R 6G6,
Canada.
Although all possible care has been placed in
assuring the accuracy of the contents of this mag-
azine, including all associated source code, listings
and figures, the publisher assumes no responsibil-
ities with regards of use of the information con-
tained herein or in all associated material.
Contact Information:
General mailbox:
Editorial:
Subscriptions:
Sales & advertising:
Technical support:
Copyright © 2002 Marco Tabini & Associates,
Inc. — All Rights Reserved
H
ere we are. After months of
preparations—and a few
sleepless nights—you hold in

your hands the very first copy of
php|architect!
While most editors will spend
their first editorial explaining at
length the arduous path the
brought the fruit of their labor to
life, I feel I have a higher goal to
aspire to. Getting php|a off the
ground has introduced us to
some genuinely new experi-
ences—nothing beats being
awake at two o’clock in the
morning (when you couldn’t
read the lettering off a truck if it
hit you) trying to pick a highly
legible font that will work both
on the screen and in print. Still, I
don’t think you want to hear
about that.
Let me, instead, give you an
idea of how this issue is organ-
ized, so that you can take advan-
tage of it to its fullest potential.
We chose PDF and electronic
distribution as a move that, we
thought, would drive down our
costs and, in turn, make it
affordable for anybody in the
world to subscribe or buy a sin-
gle issue of php|a. Still, we rec-

ognize that there are some
unique challenges related to
using this distribution strategy,
and we have taken a few steps
that (we hope) will make it easi-
er for everyone to enjoy our
magazine.
The PDF file that you have
received has been designed
both for on-screen viewing and
for printing on a regular inkjet or
laser printer. This way, you can
look the contents over directly
on your computer, and you can
print whatever interests you—or
the whole thing, if you like the
feel of paper in your hands. In
fact, although the PDF file itself
is encrypted and you should not
redistribute it electronically, you
can print as many copies of it as
you like.
If you decide that on-screen
viewing is your bag, then here
are a couple of pointers. Most of
our articles are hot-linked to the
Internet—whether it’s an e-mail
address to contact an author or
the URL of a website from which
you can download some great

information. Links are an oppor-
tunity for us to offer you some-
thing that a print magazine will
never be able to—a direct con-
nection to the world. Naturally,
all our advertisements are also
linked—so, show us your sup-
port and do visit our advertisers’
websites. They all offer great
products. No, really, they do!
To make the navigation easier,
you will find a full table of con-
tents, which can be accessed
from within Acrobat’s book-
marks tab.
Notwithstanding all these
steps we’ve undertaken, PDF
remains a “new” way of publish-
ing a magazine, and we can only
hope to get better with time.
Your feedback in this process is
crucial—we want to hear what
we’ve done right, but, especial-
ly, we want to hear what we’ve
done wrong, so that we can fix
it. Drop us an e-mail at
and let us
know what you like and don’t
like, what topics you want to see
discussed in future issues and

any comments you may have
about this month’s articles.
Happy reading!
NNEEWW SSTTUUFFFF
NEW STUFF
Open-source Gets a Rap-around
As open-source software becomes more and more
accepted as a viable alternative to its commercial coun-
terpart in IT industry, it’s becoming painfully obvious
that it’s necessary to build an infrastructure to facilitate
the exchange of information between developers and
customers.
Thanks to its open
nature, OSS lends itself
well to customization—
something that is nor-
mally unthinkable with
commercial products.
Since there is no licens-
ing cost, companies find
it easy to use open-
source projects as the
basis for larger initiatives
that have very specific
requirements. This
results in ad-hoc solu-
tions that are based on
solid, well-tested code
and can be deployed in
a short time.

Open-source developers are in the unique position of
possessing the knowledge needed to successfully mar-
ket customization and special features to their software
packages. Unfortunately, they often suffer from a lack
of exposure that would allow them to defray develop-
ment costs of new features by offering such features to
multiple customers at the same time.
Marcheka Software Ltd. aims at filling the void
between OSS vendors and clients through their Rap-X
offering, which can be found at .
Labeled as a “collaborative sales & support platform”,
Rap-X works by allowing prospective clients to make
requests for new features to be added to software pack-
ages in a collaborative way, so that multiple requests for
similar changes can be merged into a single one and
the development costs can be amortized among sever-
al players.
With this approach, everyone ends up a winner:
developers get the exposure they need and can open
new markets for their products while still benefiting the
public at large by keeping their products free.
Customers, on the other hand, benefit from the fact
that they can enjoy customized software at a fraction of
the costs normally associated with it.
Rap-x, which already counts five different open-
source projects among its clients, is offered both as an
ASP (as in Application Solutions Provider, not Active
Server Pages!) product and through a more traditional
licensing model. You can find its website here.
PHP 4.3 Inches Nearer

With the release of RC 2 at the end of November , the
new PHP version 4.3 is one step from its final release.
The new version of our beloved language includes sev-
eral enhancements and performance optimizations
compared to its predecessor. Our favorite one is the
ability to fetch SSL-protected pages directly through
the fopen() URL wrappers—a major step forward, in
our opinion, toward making PHP ever more appealing
for commercial applications.
You can download PHP 4.3 RC2 from the PHP
Group’s main page.
Sessions, Anyone?
Farpointer Technologies has released a new session
management tool for Apache called iConductor. Yes,
we know, PHP already supports session management.
iConductor, however, is interesting because it does so
independently of PHP (or any other language) by hook-
ing directly into Apache. This makes it possible, for
example, to manage sessions directly from within
HTML pages, which, in turn, could mean lower over-
head when processing pages.
iConductor costs $1,295.00 and is available directly
from Farpointer at .
December 2002 · PHP Architect · www.phparch.com
5
You’ve got a great software
product and committed users,
but you need additional fund-
ing to develop the features
they require.

php|a
PPHHPP-WWIINN
F
or a vim addict (recently converted to using gvim
and the open-source CREAM extension) like myself,
GUI IDEs are something to look at with an air of suspi-
cious resentment. On one hand, they often look easy to
use and user-friendly (something that can’t really be
said about vim). On the other, however, my shell junkie
friends and I fear that, as soon as you need to do some-
thing out of the ordinary, they will turn into rigid mon-
sters that won’t allow you to move past their pre-set
functionality.
Luckily, I’ve had a chance to find out that it’s not nec-
essarily always the case. After having been scarred for
years by Microsoft’s Visual Studio IDE, I had a chance to
use Zend Studio, which I found extremely powerful
(particularly in its debug functionality, which are very
valuable), although made a little slow by the fact that
it’s based on Java. Still, even for its price, Zend Studio is
extremely good—and works across multiple platforms.
A few weeks ago, I came across Davor Pleskina’s PHP
Editor (DPHPE from now on), which is available from
his website at . Davor is a
great guy (he’s also the author of this month’s article on
catalogue management), and he suggested that I give
his IDE a try.
Firing Up
DPHPE is extremely easy to install, although it does-
n’t come with a setup program of its own. You do have

to manually copy the files from the ZIP file you can find
at Davor’s website into a folder on your PC and create
the necessary shortcuts. I can’t see this as being a huge
problem, since it’s safe to assume that you probably
have some level of confidence with the OS if you’re
interested in this product. Still, creating a setup pro-
gram is not a particularly challenging endeavor these
days—there are plenty of tools for that—and a more
guided approach to installation would probably benefit
most users. To give you an example, during my first
attempt at running DPHPE, I simply executed the appli-
cation’s main executable from directly within WinRAR
(my compression application) without copying any
supporting files. The results were not catastrophic—the
application was running fine for the most part—but I
had lost access to some functionality, such as keyword
autocompletion.
Once installed, DPHPE takes up very little space on
PHP-WIN
December 2002 · PHP Architect · www.phparch.com
6
Reviewed For You
Davor’s PPHP Editor
By Arbi Arzoumani
DPHPE is also able to main-
tain a list of all the variables
that are currently in scope in
your script...
PHP-WIN
Davor’s PHP Editor

your hard drive, which luckily also means that it uses
very little RAM when it has to run. As much as this does-
n’t seem to be a big problem these days, if your
machine is running a number of different services at the
same time, the last thing you need is another applica-
tion that gobbles memory.
Basic Features
Where do I begin? DPHPE has a wide array of differ-
ent features that are undoubtedly helpful for any devel-
oper. Most impressive of all, these features are imple-
mented in a simple and efficient way, so that they actu-
ally help without getting in the way (at least most of
the time). The editor that comes with the application
features syntax highlighting (for HTML, PHP, Javascript
and CSS), and its aspect is fully customizable—both
from the point of view of the fonts used and of the
colours in which the syntax is rendered. Also featured in
the editor is the ability for auto-completion of key-
words, which is particularly useful for a language as
complex as PHP. It is also possible to have the applica-
tion create a list of functions defined in your scripts,
although this doesn’t always work well—for example, I
had a comment that contained the word “function”,
and the editor mistakenly recognized it as a declara-
tion.
DPHPE is also able to maintain a list of all the variables
that are currently in scope in your script (although,
unfortunately, it is unable to extend this capability to
any include files you may be using) and to automatical-
ly pop up a window that allows you to choose a vari-

able whenever you type the dollar sign. This feature
tends to be a bit annoying after a while, but it can be
turned off and the variable list can be used manually as
needed.
My only real beef with the editor is that I couldn’t
find a way to word-wrap my long lines of code. Not
everyone uses this feature, but I find it very convenient
and not having it makes it a bit difficult to use the edi-
tor in a comfortable way.
December 2002 · PHP Architect · www.phparch.com
7
Another well-developed fea-
ture of DPHPE is the ability to
create and maintain projects.
PHP-WIN
Davor’s PHP Editor
Project Management
and Web Preview
Another well-developed feature of DPHPE is the abil-
ity to create and maintain projects. A project is simply
a repository of files but, contrary to a folder, it also pos-
sesses a number of properties that make it possible, for
example, to preview entire web projects at
the click of a mouse. What’s most interest-
ing, however, is that the concept of projects
lays the foundation for a number of future
expansions, such as encoding, CVS or
SourceSafe compatibility, global search and
replace, and so on, that could all be accessi-
ble at the click of a mouse.

Speaking of web preview, if you have
Internet Explorer installed on your machine
(which you must have, unless you’re run-
ning some ancient version of Windows),
DPHPE is capable of interfacing to it and
visualizing your PHP scripts by executing
them through your web server. If you prefer,
you can also launch IE separately rather than
within the editor.
Unfortunately, DPHPE does not feature an
internal debugger—and I personally think
that this should be a very important future enhance-
ment. Still, this application offers a great deal of func-
tionality at a very convenient price—it’s free. What’s
more, there is no big corporate presence behind it, so
that it really evolves following the needs of its users,
and Davor does a great job of listening.
December 2002 · PHP Architect · www.phparch.com
8
php|a
FFEEAATTUURREESS
FEATURES
December 2002 · PHP Architect · www.phparch.com
9
T
o start, let’s consider the reasons why we should be
concerned with Performance Management. In a
nutshell, it can be summarized with two simple goals:
1) Save Money
2) Happy Customers

Although this may seem obvious, or even trite, it is
important to keep in focus when evaluating and
deploying performance-related products.
To take it one level deeper, let’s understand the issues
faced by IT managers and webmasters today:
·
High expenses for hardware and software pur-
chases to support http site traffic
·
High expenses for database server hardware
and software
·
IT administration time and money spent to
reconfigure and maintain server farms
·
Low customer satisfaction resulting from unrea-
sonable latency time and load time
With these issues in mind, we can now more clearly
attack the question of how to achieve improvements
for our projects.
Options For Performance
Management
There are many different ways through which you
can squeeze more juice from your limited hardware
server resources. These options include hardware, soft-
ware, and networking alternatives. We’ll highlight each
of these options below. Note that these alternatives are
not mutually exclusive.
Hardware Options
More Hardware - The most common indicator –

aside from emails from angry site users – that raises a
red flag about performance issues is maxed out CPU
utilization. And when this happens, an obvious but
costly solution is simply to buy more hardware. If you
have two dual-CPU http server machines whose CPU’s
Performance
Management
Opportunities
By Zeev Suraski and Brad Young
Why Focus on Performance Management? A look at the various alternatives that exist in today’s complex
IT world to improve server performance for sites that run PHP.
As Yogi Berra famously stated,
“It’s hard to make predictions,
especially about the future.”
For PHP, however, there are
some things that are not so
difficult to predict.
FEATURES
Performance Management Opportunities
are maxed out, then adding a third machine, with load
balancing, will alleviate some of this load stress. It is
worth noting that this solution works for steady state
performance issues, but does not scale well for spiked
performance issues. For example, if your site experi-
ences dramatic increases in requests at specific times of
the day, you’ll need to add enough hardware to cover
the ‘worst-case’ load. (Actually, it is more accurate to
call this the ‘best-case’. We want more traffic on our
sites, after all.)
Smarter Hardware – Similar to adding more hard-

ware, adding smarter hardware can provide perform-
ance improvements. This includes the more obvious
steps of having machines with faster CPUs, or more
CPUs per machines. Beyond that, there is also hardware
components such as disk drives with built-in memory
caching that also help improve hardware performance.
Hardware Devices – Another hardware option to
improve performance is to utilize hardware devices that
have built-in algorithm circuitry. For example, perform-
ing SSL encryption using software on your http server
adds a significant stress to the CPU load. You can add a
hardware card that performs this encryption without
requiring any CPU time, thus lowering the effective
load. Similarly, this can be done for gzip compression as
well.
Faster Code
It is clear that if your code is faster and more efficient,
you’ll be able to handle more requests with the same
hardware. Let’s explore how we can make code run
faster.
C Libraries– The massive adoption of PHP has come
about mainly due to its ease of adoption – both from a
cost perspective as well as a development perspective.
But while PHP speed has improved tremendously, it is a
fact that C code runs faster. So if you develop some of
your more algorithmically-complex functions in C and
call out to them from within your PHP scripts, you can
speed up your code. Of course, by doing this, you give
up some of the flexibility, transportability and ease of
use that brought you to PHP in the first place.

Write Better Code – Better coding practices, while
tiresome at times to adopt, pay off in the long run.
Always stay up to date and aware of the best ways to
use PHP by following email lists from php.net and read-
ing tutorial materials at sites like PHPbuilder.com and at
the Zend Developer Zone (devzone.zend.com)—not to
mention the pages of php|a, of course!
Code Acceleration – PHP is an interpreted scripting
language. This means that each time a PHP script
needs to run, the core Zend Engine will parse that file
and compile it in memory, then execute it. Since the
PHP scripts themselves typically don’t change from
request to request, this parsing and compilation phase
is repetitive and wasteful. Code Acceleration products
available today can eliminate that redundancy by main-
taining the compiled version of the file in memory.
Output Content Caching
Imagine that your friend asked you what the headline
of the New York Times was today. To respond, you go
outside, walk two blocks to the nearest news-stand,
read the headline of the New York Times, then come
back and tell him what that headline says. (We leave it
to you to understand why your friend would ask this,
but just go with the analogy).
Now, imagine that another friend calls you and asks
the exact same question. Would you repeat the journey
down to the news-stand? Unless you are madly in love
with the salesperson, probably not. You are smart
enough to identify that this new request is identical to
the previous request, and hopefully you are also smart

enough to remember what the headline was.
Well, unfortunately your http server is not as smart as
you, and it, figuratively speaking, is probably making
way too many trips down to the news-stand (read:
database server). This is where content caching comes
in. The idea of content caching is straightforward: your
server works hard to generate some results to a specif-
ic request. Then it keeps those results on hand, and if it
gets a similar request, it re-uses the previously generat-
ed results. It is interesting to note that caching takes
place at the http server level and reduces load on that
server, but an even bigger load savings is experienced
on the database server, which sees dramatically less
SQL requests coming in.
The concept is simple enough, but with all things
programmatic, the devil is in the details. The challenge
mainly boils down to:
· Cache Hit Identification – How does the cache
determine if this is indeed a similar request, or
is it a different request (i.e. Is my second friend
asking for the same headline, or is he asking
December 2002 · PHP Architect · www.phparch.com
10
PHP is an interpreted script-
ing language. This means
that each time a PHP script
needs to run, the core Zend
Engine will parse that file and
compile it in memory, then
execute it.

FEATURES
Performance Management Opportunities
about the New York Post, or is he asking about
yesterday’s New York Times, or is the headline
different for him because he gets the national
edition instead of the local edition)?
· Cache Management – How does the cache
manage the information results that are on-
hand, purge old information, and prevent
over-use of system resources (i.e. I can’t
remember every headline of every newspaper
from every day without my head exploding, so
which is the best to forget)?
Now let’s look at a few ways of achieving content
caching:
File-level Content Caching – If you have web pages
that appear the same to many users, you can store the
entire results of the URL request coming in to your http
server, as shown in Figure 1.
For example, imagine a page that lists news head-
lines, such as cnn.com. New headlines are added, per-
haps at a rate of one new headline per 15 minutes.
CNN could cache the headlines page or at least 5 min-
utes. Now, if 1,000 page view requests come in during
December 2002 · PHP Architect · www.phparch.com
11

Figure 2 - Partial Page Caching



Figure 1- Content Caching Schematic
FEATURES
Performance Management Opportunities
that 5 minute period, only one actual PHP execution
and one database access will occur, a dramatic
decrease compared to the 1,000 that would otherwise
occur. All the other requests are served directly from
the cache, as if it was a static html file. And by having
a time limit to this cached file, the worse case scenario
for content freshness would be that it would take a new
headline 4 minutes and 59 seconds to make it to the
site.
When exploring solutions, you’ll want to make sure
that there is sufficient flexibility for determining what
should be considered a ‘cache hit’. Besides the basic
URL address, you might also take specific cookie vari-
ables, GET parameters, or global http variables into
consideration. For example, you might want to cache a
different version of your home page for each geograph-
ic region, or type of user.
Partial PageCaching – Solving the “Welcome,
UserName” Problem– The benefits of file-level content
caching are clear. But often, some portions of the page
are personalized on a per-user basis. Let’s call this the
“Welcome, UserName” problem. In our headline list-
ing page, the main portion of the page is the same for
each user, but now we add a personalization message
at the top of the page. We can no longer cache the
entire file, unless we don’t mind that users named Judy,
John, and Jade will get a page that says “Welcome,

Joe”, the first person to request the URL.
The solution here is partial page caching. We still can
cache the majority of the page, which in this case also
uses the most resource-intensive database queries. This
is done at an API level, in which the caching of data
segments is maintained and reused programmatically,
as shown in figure 2.
Database Intermediary Caching– A third option for
caching of results involves separating your PHP code
from the database, as shown in Figure 3. Instead, have
a separate timed job that pulls content from the data-
base and creates chunks of html files that the PHP
scripts then can read in the output results that they are
creating.
This solution adds some complexity with regards to
system configuration and code dispersal, but the results
will sometimes make it worthwhile.
December 2002 · PHP Architect · www.phparch.com
12


Figure 3 - Database Intermediary
Publish your data fast with PHPLens
PHPLens is the fastest rapid application tool you can find for
publishing your databases and creating sophisticated web
applications. Here’s what a satisfied customer, Ajit Dixit of Shreya
Life Sciences Private Ltd has to say:
I have written more than 650 programs and have almost covered 70% of MIS,
Collaboration, Project Management, Workflow based system just in two
months. This was only possible due to PHPLens. You can develop high

quality programs at the speed of thinking with PHPLens
Visit phplens.com for more details. Free download.
Connect
with your database
PHP 5.0, with its new Zend
Engine 2, will include new
object handler capabilities
that will not only make coding
easier, it will also speed up
application performance.
FEATURES
Performance Management Opportunities
Database Optimization
Data Models and SQL Tuning – As programmers,
we often find ourselves focusing on our area of expert-
ise – coding. However, even the fastest optimized algo-
rithm as written in PHP can’t make up for the time
wasted by poorly written SQL statements or queries to
databases that are not modeled or indexed properly.
Don’t fall into this trap. As mentioned earlier under
the subject heading of “Write Better Code”, take the
time to learn about how to get the most out of your
database server. If you have a DBA in house, use his or
her expertise. As with content caching, a little effort can
go a long way when you tweak your database usage.
Data Compression
Gzip Compression – “Performance problems” is a
big umbrella. Sometimes, the performance issue is not
necessarily server throughput or CPU utilization, but
rather end-user experience of download time. Slow

download may result from either large data transfer, or
overutilization of server bandwidth. In both cases, you
will improve end-user performance experience by com-
pressing your data.
Most browsers today can receive compressed con-
tents, and will decompress automatically. Using output
compression is as simple as setting zlib.output_com-
pression = on in php.ini. Browser detection will deter-
mine if gzip support is built in, or if the original plain
text should be sent.
However, it is important to note that this adds some
additional CPU burden to your server, which must per-
form a gzip compression for each result being deliv-
ered. This can be overcome by using a compression
solution that is integrated with content caching. In this
case, the compressed version is cached, and not regen-
erated each time.
Network Infrastructure
While it isn’t directly related to PHP dynamic content,
it is worth noting that network optimization solutions,
such as those provided by Akamai , can boost content
delivery time. This can be especially useful if image
download and delivery time is your performance bot-
tleneck.
Which Should You Choose?
As stated in the opening of this article, these options
are not necessarily mutually exclusive. So, how do you
make choices on how to boost your performance?
Well, in the words of the anthropologist Margaret
Mead, “Always remember that you are absolutely

unique, just like everyone else.”
First, identify what specific problems you are having.
Also, identify the resources and infrastructure you have
available. Once you measure these parameters, select-
ing the various products or methodologies mentioned
above becomes much easier.
Enterprise Performance – Future
Directions
As Yogi Berra famously stated, “It’s hard to make pre-
dictions, especially about the future.” For PHP, howev-
er, there are some things that are not so difficult to pre-
dict.
·
First, Apache 2.0 adoption may start to grow,
when the Apache stability as well as the PHP
stability on top of Apache 2.0eventually reach-
es the necessary level. We may see some boosts
to performance from Apache 2.0’s multi-
threaded capabilities, on platforms such as
Solaris.
·
PHP 5.0, with its new Zend Engine 2, will
include new object handler capabilities that will
not only make coding easier, it will also speed
up application performance.
·
In the database world, newer extensions and
support for MySQL 4 and Oracle will likely give
another shot in the arm for database through-
put.

Why Performance Management
Matters
We opened this article explaining the benefits that
Performance Management brings you and your organ-
ization: Save Money and Happy Customers.
But the importance runs even deeper. Collectively,
the PHP community is proving every day that PHP is
ready for front-line, enterprise-level applications.
Implementing performance management solutions
such as those highlighted here bring us further towards
the recognition from the marketplace that PHP is here
to stay.
December 2002 · PHP Architect · www.phparch.com
13
Zeev Suraski has been working for over five years on the
PHP project. Along with Andi Gutmans, he started the PHP
3 and 4 projects and wrote most of their infrastructure and
core components, thereby helping to forge PHP as we know
it today and attracting many more developers to join the
movement. Zeev is a co-founder and CTO of Zend
Technologies Ltd, the leading provider of development and
performance management tools for PHP-enabled enterpris-
es. Brad Young leads the Product Management team at
Zend, and has over 15 years experience in on-line database
and XML systems deployment. You can reach both Zeev and
Brad via Zend's website at www.zend.com.
php|a
FEATURES
14
FFEEAATTUURREESS

December 2002 · PHP Architect · www.phparch.com
I
n a world of web-based management systems and
graphical user interfaces, it’s comforting to find out
that shell programming is still regarded as an important
piece of the IT puzzle. Don’t get me wrong—I’m not
saying this merely out of nostalgia for the times when I
had to make do with 48kB of RAM for operating sys-
tem, program and data, or had to wrestle a few cycles
of program execution out of a mainframe. Text-based
applications are still very useful in a number of situa-
tions, particularly when simplicity is called for or a GUI
would be oppressively slow to deal with (such as when
you’re trying to manage a web server that is heavily
loaded and cannot spare much bandwidth for you).
Shells, particularly (but not exclusively) in the UNIX
world, are very much alive and kicking, and have
advanced significantly in complexity and functionality
over the past few years.
nCurses - A Library For
Cool Shell Apps
Think “shell application” and the image of a dull,
black-and-white text screen comes to mind. Luckily,
most terminals are actually capable of a lot more than
just displaying text: they provide a variety of colours
and effects (such as underlined or bold—”bright”—
text), mouse compatibility and much more. It’s normal-
ly rather difficult, however, to take advantage of these
capabilities for a number of reasons. First, not all termi-
nals are created equal—there are several different stan-

dards available, each with its own commands and
capabilities. Second, because terminal systems have to
work over simple serial communication lines, the com-
mands they support are often intricate combinations of
ASCII characters. Since shell applications are usually
written as a quick and easy solutions to simple prob-
lems, the developers rarely have the time and patience
to bother with adding the “frills” to their interfaces.
Those of you who, like me, have spent their youth
wasting their allowances on telephone bills as a result
of the expensive hobby known as “BBS”, however,
know what terminals are capable of. Remember the
cool menus, the dazzling animations and the colourful
interface? Compare that with your average shell appli-
cation and, well, I’d take the BBS over it every day.
On UNIX systems, the capabilities of terminals are
stored in the termcap database, a file usually found in
the /etc directory that is used by applications such as
the original vi editor. Termcap contains a description of
each terminal that is recognized by the system (for
example, “dumb” or “ansi-compatible”), together with
the commands it supports.
Termcap, however, is not in a very “developer-friend-
ly” format. In fact, I think it’s fair to say that using it in
Curses!
Writing CCool SShell
Applications WWith PPHP
By Marco Tabini
While PHP is most widely used as a Web development language, I find that it works very well as a shell tool, too. In fact,
I’d have to say that PHP is my favourite shell language, and that I prefer it over typical shells or even Perl (although the lat-

ter is rather unbeatable when you have to process large data files).
PHP Version: Latest PHP CVS Build
O/S: nCurses-compatible O/S
Web server: N/A
Support Tools: nCurses Library
REQUIREMENTS
FEATURES
December 2002 · PHP Architect · www.phparch.com
15
an application with no outside help would require a
major effort, since you would only have to interpret its
contents, but also write the necessary functions to han-
dle tasks like cursor positioning, text attributes, window
management, and so on.
It was probably out of desperation that, around
1980, a student at UC Berkley named Ken Arnold devel-
oped a series of routines that provided an essential
framework for terminal interface development and col-
lected them in what became known as the “curses”
library. Curses then became the basis for Rogue, possi-
bly one of the first-ever Role Playing Games, initially
developed for BSD Unix but eventually ported to pret-
ty much any operating system ever conceived. If you
have never played Rogue, I suggest you give it a try—
not only it’s a thoroughly enjoyable and never repeti-
tive game, but it also gives you an idea of how engag-
ing a simple text-based user interface can be. You can
find Rogue in RPM format at :
/>search.php?query=rogue
I should warn you that you will find it highly addic-

tive; your productivity will probably drop to zero for a
while, but you’ll have lots of fun in the bargain.
The Curses library was picked up by Bell Labs, which
included it in its System III version of UNIX, introducing
several changes to termcap in the process. Termcap’s
new format, called terminfo, offered more functionali-
ty. Additional development was done through the
1980s, and in 1993 the package was finally renamed
ncurses.
Ncurses and PHP
The ncurses library provides a number of features,
such as:
· Formatted input and output on a variety of ter-
minals
· Support for colours and various text styles, such
as underline, bold, and so on
· Support for windowing
· Support for mouse input
PHP support for the ncurses library is still very much
in its infancy, and is based on the GNU implementation
of the library, available via FTP at:
/>Curses! Writing Cool Shell Applications With PHP
Proven Open Source Expertise
• When you need to deploy a web-serving
framework capable of delivering millions of views
and transactions per day...
• When you need to construct complex document
and task workflows that match your organizations'
needs...
• When you need to create a world wide streaming

network capable of 99.99% up time...
• When you need to protect your country's
sovereignty by avoiding "random" changes in
software licensing that can affect the price of
each transaction your citizens make...
• When you need the level of security that only
expertise and transparency can provide you...
• When you need Single-Sign-On across multiple
vendors serving a diverse constituency...
• When you need to reduce your reliance on
proprietary software solutions and realize the
promise of your existing investments...
The Tribal Knowledge Group's demonstrated
credentials in the Open Source Software
community enable them to provide you with
decades of software engineering, architecture,
security and strategy expertise via an
unprecedented think-tank of Internet
technology and open-source experts.
Contact us at to
learn how the Tribal Knowledge Group can help
maximize your existing investment for
the future.
FEATURES
16
December 2002 · PHP Architect · www.phparch.com
Curses! Writing Cool Shell Applications With PHP
It was originally introduced by Hartmut Holzgraefe
and Georg Richter with version 4.1.0 of PHP and is still
considered highly experimental, to the point that the

official PHP documentation covers the ncurses func-
tions only very quickly and in a still incomplete fashion.
Luckily, the ncurses extension functions follow their
original counterparts very closely, which actually makes
the process of creating an ncurses-powered PHP script
very easy (this is something that the authors of the
extension must have undoubtedly known, so that they
have—correctly, in my opinion—put all their efforts in
building out the extension).
Ncurses is actually supported on a number of plat-
forms, including all the UNIX derivatives, cygwin and
BeOS.
Obtaining the Right
Version of PHP
The problem with making ncurses run on your server
is that, in order to gain access to enough functionality,
you will have to download the most recent version of
PHP from the public CVS tree. There is no way around
this problem, as the stable releases available to this
point do not yet include the latest code, which is unfor-
tunately necessary to perform most of the basic ncurs-
es tasks.
Luckily, obtaining the latest version of PHP is not dif-
ficult at all. You can get it directly by issuing a couple of
CVS commands, which are clearly explained in the
manual:
If all goes well, you should end up with a sub-folder
of your current directory called php4. Simply cd into it
and configure PHP as you would normally, ensuring
that you include

--with-ncurses
to your invocation of
configure, and that you compile the CLI version of
PHP—after all, I’m afraid that you would have little use
for the ncurses extension in a web application.
Our First ncurses Application
It’s now time to test whether the installation went
smoothly by executing the simple PHP script that you
can see in Listing 1. This script is designed to be run
from the shell. As such, it includes a “shebang”, that is,
a specially-formatted comment (always the first line of
the script), that instructs the shell as to which inter-
preter this file should be executed through. This
approach works only on UNIX-type shells, however, so
if you’re running Windows you’ll have to use the cyg-
win shell rather than the DOS command prompt.
If you do not receive any errors, you should see the
words “Hello World!” written in red text over a cyan
background appear at the top of your screen for a few
seconds and then disappear. If something goes wrong,
there’s a good chance that your shell will become unus-
able—don’t panic, this is quite normal, as we’ll see in a
few moments.
As you can see, even a simple Hello World application
requires quite a bit of code if you write it using ncurs-
es. You not only have to initialize the library using the
ncurses_init() function, but you have to create a
combination, or “pair”, of each foreground and back-
ground colours that you want to use in your applica-
tion. This, in turn, will only work if the terminal you are

using supports colours to start with, and the ncurs-
es_has_colors() function provides the script with
that information.
Even writing a string to the screen requires a call to a
specialized ncurses function, ncurses_addstr().
The latter is actually part of a family of functions that
make it possible to manipulate text on the screen.
Incidentally, you will also have noticed that it’s neces-
sary to forcefully refresh the screen in order for any
updates made to it to become visible. This particular
aspect of ncurses programming is actually designed so
that only the minimum amount of commands are sent
to the screen, and only when necessary—thus reducing
the amount of data sent to the terminal by as much as
possible. With today’s fast connections, this may sound
a bit ridiculous, but you have to understand that ncurs-
es must be able to work efficiently even over slow seri-
al connections—and a bit of optimization never hurts.
Thus, for the most part, an application writes to a “vir-
tual screen” and then issues a call to
ncurses_refresh() when all of its updates are com-
plete and it is ready to show its output to the user.
Finally, the ncurses library must be explicitly terminat-
ed by calling ncurses_end(). This is necessary
because ncurses captures the terminal and creates its
virtual screen over it. As a result, exiting from a script
without also terminating ncurses results in a terminal
that, in most cases, is completely unusable.
The problem of course, is that sometimes scripts end
unexpectedly, as it is often the case when errors occur.

For this reason, it’s always a good idea to create your
own error handler that explicitly calls
ncurses_end() before aborting your script. This will
not protect you from all kinds of problems (parse errors
will still cause PHP to exit without calling your handler,
for example), but it will take care of at least some cases.
With the exception of windowing functions, which
we’ll examine in the next section, all ncurses functions
return true if an error has occurred (they actually return
an integer value different from NCURSES_ERR, which is
defined as zero).
cvs -d :pserver::/repository login
cvs -d :pserver::/repository co php4
FEATURES
December 2002 · PHP Architect · www.phparch.com
17
Curses! Writing Cool Shell Applications With PHP
Windowing
One of the most interesting characteristics of ncurses
is the ability to create and manage multiple windows.
Although they cannot overlap each other, each window
possesses its own “virtual screen” and can be modified
and refreshed independently of its other counterpart
on the terminal.
As an example, let’s take a look at Listing 2, which
introduces a number of new ncurses functions. The first
one is ncurses_getmaxyx(), which returns the
dimensions of the virtual screen. You have probably
noticed that, in this function, the height is listed in the
function call before the width—something that may

appear unnatural to someone who is used to working
with GUI systems. All ncurses functions follow this con-
vention, however, and it does take a while to get used
to it.
Also, the call to ncurses_getmaxyx() at the
beginning of Listing 2 uses a constant called STDSCR.
This constant describes, by convention, a pointer to the
main virtual screen, which is, for all purposes, a window
of its own right. In fact, most of the ncurses functions
that manipulate the virtual screen also have a window-
specific counterpart—for example,
ncurses_addstr() and ncurses_waddstr(). In
most cases, the ncurses library implements the virtual-
screen version of these functions as simple macros to
the window versions with the hardcoded STDSCR
parameter.
The ncurses_newwin() function is used to create
a new window. Its syntax is as follows:
Its result is an ncurses resource that you can use in
subsequent calls to other ncurses functions that can
manipulate the contents of your newly created win-
dow, such as ncurses_wborder, which—you guessed
it—creates a border around the frame of our window:
With the exception of the first parameter, which iden-
tifies the window where the border is to be drawn, each
of the other parameters represent the characters that
the function must use to build the border. If you leave
all these parameters as NULL or zero, ncurses_wbor-
der() will create a standard (and classy) border
around the window. If, for example, you call the func-

tion as follows:
You will obtain a slightly less pleasant—but just as
functional—border.
Writing into a window is performed through a num-
ber of functions. The simplest one is
ncurses_waddstr(), which is functionally equal to
ncurses_addstr(), with the exception that it takes
a window resource as the first parameter. In the case of
Listing 2, however, I have used a slightly more complex
version of it called ncurses_mvwaddstr(), which at
the same time moves the cursor to a pre-defined posi-
tion and prints out the string passed to it:
As you may have noticed, the x and y coordinates
passed to this functions reference the top-left hand cor-
ner of the window—not of the screen. There is, natural-
ly, an equivalent of ncurses_mvwaddstr() that
works with the virtual screen and is called
ncurses_mvaddstr(). This, in turn, is functionally
equivalent to calling ncurses_mvwaddstr() as fol-
lows:
Finally, we come to the visualization of windows,
which is achieved by calling the ncurses_wre-
fresh() function. Keep in mind that ncurses does not
handle windows the same way a GUI system like
resource ncurses_newwin (
int $height,
int $width,
int $y,
int $x
);

int ncurses_wborder (
resource $win_resource,
int $left_side,
int $right_side,
int $top_side,
int $bottom_side,
int $top_left_corner,
int $top_right_corner,
int $bottom_left_corner,
int $bottom_right_corner
);
ncurses_wborder ( $win1,
‘|’,
‘|’,
‘-’,
‘-’,
‘+’,
‘+’,
‘+’,
‘+’ );
int ncurses_mvwaddstr (
resource $win_resource,
int $y,
int $x,
string $str
);
ncurses_mvwaddstr (
STDSCR,
$y,
$x,

$str
);
FEATURES
18
December 2002 · PHP Architect · www.phparch.com
Curses! Writing Cool Shell Applications With PHP
Windows or XWindows would; this means that the
overlapping of windows and features like z-order are
not normally provided to the developer (although
another portion of ncurses called panels, which is also
being implemented in the PHP extension, does provide
exactly this functionality). Thus, wrefresh() should
simply draw a particular window on the screen, as if it
were in focus and with complete disregard for whatev-
er other windows may overlap with it. I say “should”
because in reality different versions of ncurses behave in
different ways—as such, it’s best to either use only tiled
windows, or to use one window at a time on top of the
virtual screen.
Thus, calling wrefresh() will cause a window to be
drawn ontop of the virtual screen, in our cases advising
us that its contents are rather messy.
Another interesting characteristic of ncurses is that it
provides no scrolling capabilities. When you reach the
end of the screen (or of a window), text is simply dis-
carded. Depending on the type of application that you
are writing, this could be a major problem—but it can
be easily solved as we’ll see later on.
A Bit of Colour and a
Sprinkle of Fairy Dust

As marketing people have known for years, colour
makes all the difference. In a well-designed interface,
proper colour management can make any application
easier to use (except for vim, which was obviously writ-
ten by aliens) and more pleasant to the eye.
The ncurses library provides an extensive set of func-
tions that deal with the aspect of text—not only with its
colour, but also with its intensity and style. For exam-
ple, Listing 3 produces text in quite a variety of styles.
Because colours can only be rendered on some termi-
nals, the ncurses extension provides the
ncurses_has_colour() function to determine
whether colours can, in fact, be used on the current ter-
minal. Also, colour rendering has to be enabled by call-
ing the ncurses_start_color() function.
The ncurses library, as I mentioned above, handles
colours by means of “pairs”, each representing the
combination of a foreground and background colour.
Each pair is defined using the ncurses_init_pair()
function:
The ncurses extension provides a number of pre-set
colour definitions, which are shown in Figure 1. On
some terminals, it is also possible to create custom
colours by changing the RGB values associated with a
particular pre-defined colour (you could finally have
your own opportunity to invent the “greenest blue”
ever made!) through a call to
ncurses_init_color(), whose syntax is as follows:
A call to ncurses_can_change_color(), which
takes no parameters, will tell you whether you can,

indeed, change the appearance of a particular colour.
Attributes are handled in a very similar fashion to
HTML. They can be turned on using the
ncurses_attron() function (or ncurses_wat-
tron() for a window), or off through a call to ncurs-
es_attroff(). A list of available attributes is shown in
Figure 2.
Similarly to colours, there is a way to determine
whether a particular attribute is supported by the cur-
rent terminal. The ncurses_termattrs() function
takes no parameter and returns a logical OR of all the
attribute values that the terminal can handle.
int ncurses_init_pair (
int $pair_id,
int $foreground_colour,
int $background_colour
);
int ncurses_init_color (
int $color,
int $rgb,
int $green,
int $blue
);
NCURSES_COLOR_BLACK Black
NCURSES_COLOR_WHITE White
NCURSES_COLOR_CYAN Cyan
NCURSES_COLOR_RED Red
NCURSES_COLOR_YELLOW Yellow
NCURSES_COLOR_BLUE Blue
NCURSES_COLOR_MAGENTA Magenta

NCURSES_COLOR_GREEN Green
Figure 1
A_NORMAL Normal font
A_STANDOUT Standout (reverse)
A_UNDERLINE Underlined
A_REVERSE Reverse screen
A_BLINK Blinking Text
A_DIM Dimmed
A_BOLD Bold
A_PROTECT Protected
A_INVIS Invisible
Figure 2
FEATURES
December 2002 · PHP Architect · www.phparch.com
19
Curses! Writing Cool Shell Applications With PHP
Input Management
As I’m sure you can imagine, a good user interface
without input capabilities is a bit like a war with no
enemy—you could make one but it would be rather
dull and quite pointless. The ncurses library offers a
number of facilities for both keyboard and mouse
input, although we will only focus on the latter as far as
this article is concerned.
The most commonly used form of keyboard input is
ncurses_getch(), which retrieves a single character
from the input stream. Under normal circumstances,
that character is also outputted to the screen, but you
can prevent that from happening by calling the
ncurses_noecho() function. For example, take a

look at Listing 4, which shows a simple script that can
be used to control the Apache web server through a
series of simple commands.
As you can see, there are a couple of interesting func-
tions. First, I’ve created a simple msgbox() routine
that takes an arbitrary amount of text and displays it in
an ordered fashion on a window of its own. This corre-
sponds to a simple dialogue window in a GUI environ-
ment. You will notice that I have used the wordwrap()
function to ensure that the text is always properly cen-
tered and never interferes with the window’s borders.
The lack of a couple of ncurses functions (in particular
wsyncup() and wsyncdown()) in the PHP extension
make it slightly awkward to manage windowing prop-
erly, so that the application is forced to manually
refresh the screen every time a dialogue box is dis-
played.
The ncurses_getch() function is called in an infi-
nite loop until the user presses the “q” key and exits.
The result value of ncurses_getch() is not, howev-
er, a character, but an integer value. This lets you man-
age “special” characters, such as Page-up and Page-
down, more easily and conveniently—but you will have
to convert the integer value to a string if you want to
interpret it as a character. More complex input can be
1 #!/usr/local/bin/php
2
3 <?php
4
5 error_reporting(E_ALL);

6
7 // Initialize ncurses
8
9 if (ncurses_init())
10 die ("Unable to initialize ncurses!");
11
12 // Initialize colour, if available
13
14 if (ncurses_has_colors())
15 {
16 // Initialize a simple colour pair
17 // And select it
18
19 ncurses_start_color();
20
21 ncurses_init_pair (1, NCURSES_COLOR_RED, NCURSES_COLOR_CYAN);
22 ncurses_color_set (1);
23 }
24
25 // Clear screen
26
27 ncurses_erase();
28
29 // Print out something
30
31 ncurses_addstr ('Hello World!');
32
33 // Refresh the screen
34
35 ncurses_refresh();

36
37 // Wait a while
38
39 sleep (4);
40
41 // Exit
42
43 ncurses_end();
44
45 ?>
Listing 1
FEATURES
20
December 2002 · PHP Architect · www.phparch.com
Curses! Writing Cool Shell Applications With PHP
performed by calling the ncurses_instr() func-
tion, which reads an entire string from the input and
returns it.
It’s interesting, at least in my opinion, to note that
even a simple script like this one can be set as the
default command for a particular user account, thus
depriving it of shell access but still giving it the oppor-
tunity to perform certain operations—in this case, stop-
ping and starting Apache.
A More Complex Example
Let’s now move on to a more audacious attempt at
using the ncurses library to produce a complete shell-
based application. Listing 5 contains a self-contained
text file viewer that allows for up and down scrolling
(both line by line and page by page), can split and dis-

play lines of text that span multiple lines (without using
wordwrap, this time) and displays a status line at the
bottom of the screen.
This script introduces the ncurses_move() func-
tion, which is used to move the cursor to a particular
location (in fact, ncurses_mvwaddstr() is essential-
ly the equivalent of a call to ncurses_move() fol-
lowed by a call to ncurses_waddstr()).
You’ll notice that the most complicated action per-
formed by this script is the tracking of the position of
the screen’s output within the text file. For the script to
1 #!/usr/local/bin/php
2
3 <?php
4
5 error_reporting(E_ALL);
6
7 // Initialize ncurses
8
9 if (ncurses_init())
10 die ("Unable to initialize ncurses!");
11
12
13 // Get dimensions of the screen
14
15 ncurses_getmaxyx (STDSCR, $screen_height, $screen_width);
16
17 // Create a window and center it
18
19 $win1 = ncurses_newwin (20, 50, ($screen_height - 20) / 2, ($screen_width - 50) / 2);

20
21 // Clear screen
22
23 ncurses_erase();
24
25 // Clear both windows
26
27 ncurses_wclear ($win1);
28
29 // Create a border for our window
30
31 ncurses_wborder ($win1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
32
33 // Type something in the window
34
35 $output_message = "This screen is full of garbage!";
36
37 ncurses_mvwaddstr ($win1, 9, (50 - strlen ($output_message)) / 2, "This screen is full
of garbage!");
38
39 // Fill the screen with lots of text
40
41 for ($i = 0; $i < 3000; $i++)
42 ncurses_addstr ($i);
43
44 // Refresh the screen
45
46 ncurses_refresh();
47
48 // Wait a while

49
50 sleep (2);
51
Listing 2
Continued On Page 21...
FEATURES
December 2002 · PHP Architect · www.phparch.com
21
Curses! Writing Cool Shell Applications With PHP
stop scrolling at the end of the file, it is necessary to
track both the position within the file that corresponds
to the top of the screen (which we need so that we can
refresh it), as well as the position that corresponds to
the bottom of the screen. This is made more difficult by
the fact that there is no direct correspondence between
the width of the screen and the length of each line of
text, so that a single line of text can in fact correspond
to multiple lines on the screen—but we still want the
script to scroll by one screen line at a time, so that the
script has to track the correspondence between screen
display and file. To make things a bit easier, I have sep-
arated the file in its individual lines by using the
file() function.
Clearly, it would have been much simpler to load the
file in memory and then use wordwrap() on it to
51
52 // Refresh the window, thus making it visible
53
54 ncurses_wrefresh ($win1);
55

56 // Wait a while
57
58 sleep (2);
59
60 // Destroy the window
61
62 ncurses_delwin ($win1);
63
64 // Exit
65
66 ncurses_end();
67
68 ?>
Listing 2: Continued From Page 20...
1 #!/usr/local/bin/php
2
3 <?php
4
5 error_reporting(E_ALL);
6
7 // Initialize ncurses
8
9 if (ncurses_init())
10 die ("Unable to initialize ncurses!");
11
12 // Initialize colour, if available
13
14 if (ncurses_has_colors())
15 {
16 // Initialize a simple colour pair

17 // And select it
18
19 ncurses_start_color();
20
21 ncurses_init_pair (1, NCURSES_COLOR_RED, NCURSES_COLOR_CYAN);
22 ncurses_init_pair (2, NCURSES_COLOR_RED, NCURSES_COLOR_BLACK);
23 }
24
25 // Clear screen
26
27 ncurses_erase();
28
29 // Print out something using colour pair 1
30
31 ncurses_color_set (1);
32 ncurses_addstr ("Hello World!\n");
33
34 // Print out using colour pair 2 -- and make it bold
35
36 ncurses_color_set (2);
37 ncurses_addstr ("This is red\n");
38 ncurses_attron (NCURSES_A_BOLD);
39 ncurses_addstr ("This is red and bold\n");
40
41 // Try out some other effects
42
43 ncurses_attroff (NCURSES_A_BOLD);
44 ncurses_attron (NCURSES_A_UNDERLINE);
45 ncurses_addstr ("Here's some underlined text\n");
46

47 ncurses_attron (NCURSES_A_BLINK);
48 ncurses_addstr ("Underlined and blinking\n");
49
//fhh
Listing 3
Continued On Page 24...
FEATURES
22
Curses! Writing Cool Shell Applications With PHP
ensure that there would be a one-to-one correspon-
dence between the screen and the file. However, you
can take this script and turn it into a full-fledged editor
with relatively minor modifications—whereas if it were
based on the wordwrap() trick it would be much
more difficult to do so.
Where To Go From Here
There is much more to the ncurses library than what
we’ve been able to explore here. In particular, recent
versions of ncurses include two libraries, panels and
form, that can be used to manipulate overlapping (and
scrollable) windows and form fields respectively. The
panels library is already partially implemented in the
CVS tree of PHP, while there is no support for the form
library. However, they are both very important, as they
can greatly simplify the development of complex shell-
based applications. For an example of their full capabil-
ities, take a look at the Lynx text-based web browser,
which uses both libraries to their fullest potential.
December 2002 · PHP Architect · www.phparch.com
1 #!/usr/local/bin/php -q

2
3 <?php
4
5 // Create a custom error handler
6
7 function my_error_handler ($errno, $errstr, $errfile, $errline)
8 {
9 ncurses_end();
10
11 echo "$errstr on line $errline\n\n";
12
13 exit(0);
14 }
15
16 set_error_handler ('my_error_handler');
17
18 // Centers a line on the given window
19
20 function center_window ($win, $y, $text)
21 {
22 ncurses_getmaxyx ($win, $height, $width);
23 ncurses_mvwaddstr ($win, $y, ($width - strlen ($text)) / 2, $text);
24 }
25
26 // Creates a message box
27
28 function msgbox ($text)
29 {
30 // Get size of screen
31

32 ncurses_getmaxyx (STDSCR, $height, $width);
33
34 // Determine size of message box
35
36 $win_w = ($width - 6);
37 $win_h = ($height - 6);
38
39 if ($win_w > (strlen ($text) + 4))
40 $win_w = strlen ($text) + 4;
41 else
42 $text = wordwrap ($text, $win_w - 4);
43
44 $string_data = explode ("\n", $text);
45
46 if ($win_h > (count ($string_data) + 4))
47 $win_h = count ($string_data) + 4;
48
49 // Create a new window
50
Listing 4
Continued On Page 23...
Marco Tabini is co-editor of php|architect. He spends most of his time
lurking around on the PHP mailing lists and on the php|a website doing
is best to confuse fellow programmers who are in trouble. You can reach
him at
php|a
FEATURES
December 2002 · PHP Architect · www.phparch.com
23
51 $win = ncurses_newwin ($win_h, $win_w, ($height - $win_h) / 2, ($width - $win_w) / 2);

52
53 // Apply a simple border
54
55 ncurses_wborder ($win, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
56
57 // Type all the information
58
59 for ($i = 0; $i < min ($win_h - 4, count ($string_data)); $i++)
60 ncurses_mvwaddstr ($win, $i + 2, ($win_w - strlen ($string_data[$i])) / 2, $string_data[$i]);
61
62 // Refresh window
63
64 ncurses_wrefresh ($win);
65
66 // Wait for input
67
68 ncurses_getch();
69
70 // Destroy window
71
72 ncurses_delwin ($win);
73 }
74
75 // Creates the main menu
76
77 function main_menu()
78 {
79 // Clear screen
80
81 ncurses_erase();

82
83 // Create main menu
84
85 ncurses_color_set (2);
86 ncurses_attron (NCURSES_A_BOLD);
87 center_window (STDSCR, 2, "Main Menu");
88 center_window (STDSCR, 3, "---------");
89 ncurses_attroff (NCURSES_A_BOLD);
90
91 center_window (STDSCR, 4, '(1) Stop Apache');
92 center_window (STDSCR, 5, '(2) Start Apache');
93 center_window (STDSCR, 6, '(3) Restart Apache');
94 center_window (STDSCR, 8, '(Q) Quit');
95
96 ncurses_refresh();
97 }
98
99 // Initialize ncurses
100
101 if (ncurses_init())
102 die ("Unable to initialize ncurses!");
103
104 // Initialize colour, if available
105
106 if (ncurses_has_colors())
107 {
108 // Initialize a simple colour pair
109 // And select it
110
111 ncurses_start_color();

112
113 ncurses_init_pair (1, NCURSES_COLOR_CYAN, NCURSES_COLOR_BLACK);
114 ncurses_init_pair (2, NCURSES_COLOR_RED, NCURSES_COLOR_BLACK);
115 }
116
117 // Turn off echo
118
119 ncurses_noecho();
120
121 // Create main menu
122
Continued On Page 24...
Curses! Writing Cool Shell Applications With PHP
Listing 4: Continued From Page 22...
FEATURES
24
December 2002 · PHP Architect · www.phparch.com
Curses! Writing Cool Shell Applications With PHP
122
123 main_menu();
124
125 while (true)
126 {
127 $c = ncurses_getch();
128 $s = chr ($c);
129
130 switch ($s)
131 {
132 case '1' :
133 msgbox (shell_exec ("apachectl start") . "\n\nPress a key to continue");

134 main_menu();
135 break;
136
137 case '2' :
138 msgbox (shell_exec ("apachectl stop") . "\n\nPress a key to continue");
139 main_menu();
140 break;
141
142 case '3' :
143 msgbox (shell_exec ("apachectl restart") . "\n\nPress a key to continue");
144 main_menu();
145 break;
146
147 case 'Q' :
148 case 'q' :
149 ncurses_end();
150 exit;
151 break;
152 }
153 }
154
155 ?>
Listing 4: Continued From Page 23...
50 // Refresh the screen
51
52 ncurses_refresh();
53
54 // Wait a while
55
56 sleep (4);

57
58 // Exit
59
60 ncurses_end();
61
62 ?>
LISTING 3: Continued From Page 21...
FEATURES
December 2002 · PHP Architect · www.phparch.com
25
FFEEAATTUURREESS
SNMP MManagement
With PPHP
By Harrie Hazewinkel
In the last decade, the importance of distributed services has become clear, as organizations have deployed networks to auto-
mate their business processes. As a result, organizations now depend on their networks and the related services, and any
minute of down-time costs money. Not only personnel cannot perform their work during down-time, but many automated
services, such as telesales, for instance, stop working. If an organization monitors its network, it can detect problems before
they become a problem, increasing productivity and reducing personnel costs. This article provides a brief explanation of the
SNMP protocol and explains the SNMP functionality that is available through PHP.
Simple Network
Management Protocol
T
he Simple Network Management Protocol (SNMP)
provides a framework for network management.
SNMP enables access to network management infor-
mation to make, for instance, status monitoring, fault-
detection and configuration possible. Since its intro-
duction, SNMP has been used heavily to perform mon-
itoring and fault detection tasks. There has been little

use of SNMP for configuration purposes, though, since
it lacks a proper security protocol.
However, the latest SNMP framework (version 3)
defines security functionality by means of authentica-
tion, privacy and access control. These features protect
the network against threats such as:
1. Modification of an SNMP message in transit by an
unauthorized SNMP entity.
2. Modification of the SNMP message stream by
changing the order, delaying or replaying messages.
3. Masquerading of SNMP entities through the
appropriation of another SNMP entity’s identity.
4. Disclosure of management information that is
transferred between SNMP entities (users).
5. Eavesdroppers that attempt to capture the man-
agement data for other “evil” purposes.
6. Unauthorized access to particular management
information.
If you compare these capabilities with earlier version
of SNMP, which only offered a single clear text pass-
word authentication method and no encryption, you’ll
see that SNMPv3 represents a big step forward for the
protocol’s security features. What’s more, SNMPv3
defines three different security levels:
1) No authentication and no privacy
2) Authentication and no privacy
3) Authentication and privacy
It also allows for the use of different authentication
and privacy protocols, thus enabling SNMP to evolve
over time as new and better security mechanisms are

PHP Version: PHP 4 (4.3.0 for SNMPv3 support)
O/S: Any
Web server: Any
Support Tools: N/A
REQUIREMENTS

×