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

Tài liệu Building a monitoring system into your scripts ppt

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 (2.62 MB, 71 trang )

www.phparch.com
AUGUST 2003
The Magazine For PHP Professionals
Case studies in Case studies in
Client/Server ApplicationsClient/Server Applications
VOLUME II - ISSUE 8
Transforming XML to PDF Transforming XML to PDF
with the help of LaTeXwith the help of LaTeX
Embedding Assembler in PHPEmbedding Assembler in PHP
Take your PHP to new lowsTake your PHP to new lows
php|
Cruise
March 1
st
- March 5
th
2004
See inside for details
Get Ready For
Maintenance Maintenance
from the Outsetfrom the Outset
Building a monitoring system Building a monitoring system
into your scriptsinto your scripts
Plus:
Tips & Tricks, Product Reviews and much more
An Introduction to MingAn Introduction to Ming
Create amazing Flash Create amazing Flash
applications on-the-flyapplications on-the-fly
An Introduction to cURLAn Introduction to cURL
Discover the ins and outs Discover the ins and outs
of this indispensable toolof this indispensable tool


*By signing this order form, you agree that we will charge your account in Canadian dollars for the
“CAD” amounts indicated above. Because of fluctuations in the exchange rates, the actual amount
charged in your currency on your credit card statement may vary slightly. †Limited time offer
expires August 31st, 2003.
Choose a Subscription type:
Canada/USA $ 81.59 $67.99 CAD ($59.99 $49.99 US*)
International Surface $108.99
$94.99 CAD ($79.99 $69.99 US*)
International Air $122.99
$108.99 CAD ($89.99 $79.99 US*)
Your charge will appear under the name “Marco Tabini & Associates, Inc.”
The first issue of your subscription will be mailed to you in September, 2003.
Please allow up to 6 weeks for your subscription to be established.
*US Pricing is approximate and for illustration purposes only.
php|architect Subscription Dept.
P.O. Box 3342
Markham, ON L3R 9Z4
Canada
Name:
Address:
City:
State/Province:
ZIP/Postal Code:
Country:
Payment type:
VISA Mastercard American Express
Credit Card Number:
Expiration Date:
E-mail address:
Phone Number:

Buy now and save $10 off the price of any subscription†
Visit: for more information or to subscribe online.
Signature: Date:
To subscribe via snail mail - please detach this form, fill it out and mail to the address above or fax to +1-416-630-5057
php|architect
The Magazine For PHP Professionals
Existing
subscribers
can upgrade to
the Print edition
and save!
Login to your account
for more details.
NEW!
NEW!
Signup now and save $100.00!
Hurry, space is limited.
Visit us at www.phparch.com/cruise for more details.
php|
Cruise
March 1
st
- March 5
th
2004
Andrei Zmievski - Andrei's Regex Clinic, James Cox - XML for the Masses, Wez Furlong - Extending PHP,
Stuart Herbert
- Safe and Advanced Error Handling in PHP5, Peter James - mod_rewrite: From Zero to Hero, George
Schlossnagle - Profiling PHP, Ilia Alshanetsky - Programming Web Services, John Coggeshall - Mastering PDFLib,
Jason Sweat - Data Caching Techniques

<?
?>
We’ve got you covered,
from port to sockets.
Port Canaveral • Coco Cay • Nassau
Plus: Stream socket programming, debugging techniques, writing high-performance code,
data mining, PHP 101, safe and advanced error handling in PHP5, programming smarty,
and much, much more!
TABLE OF CONTENTS
4
August 2003 · PHP Architect · www.phparch.com
II NN DD EE XX
Departments
php|architect
Features
10 Transforming XML to PDF with LaTeX
Stephan Schmidt
16 Ming & PHP
Seth Wilson
33 Sockets: Part 2
Eugene Otto
41 Grokking cURL
Peter James
48 Maintenance from The Outset
Graeme Foster
57 Embedding Assembler in PHP
Igor Gorelik
5 Editorial
7 What’s New!
26 Granted!

Announcing the winners of the 2003
php|architect Grant Program
29 Datanamic DeZign for Databases 3
Peter James
65 Tips & Tricks
John W. Holmes
69 Bits & Pieces
71 e x i t ( 0 ) ;
Expect More From php|a
Marco Tabini
TABLE OF CONTENTS
EDITORIAL
5
August 2003 · PHP Architect · www.phparch.com
EE DD II TT OO RR II AA LL RR AA NN TT SS
php|architect
Volume II - Issue 8
August, 2003
Publisher
Marco Tabini
Editor-in-Chief
Brian K. Jones
brian@phpar
ch.com
Editorial Team
Arbi Arzoumani
Brian Jones
Eddie Peloke
Peter James
Marco Tabini

Graphics & Layout
Arbi Arzoumani, William Martin
Managing Editor
Emanuela Corso
Authors
Greame Foster, Igor Gorelik, Peter James,
Eugene Otto, Stephan Schmidt, Marco Tabini,
Seth Wilson
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 magazine, including all associated source code, listings
and figures, the publisher assumes no responsibilities with regards of use
of the information contained herein or in all associated material.
Contact Information:
General mailbox:
Editorial:
Subscriptions:
Sales & advertising:
Technical support:
Copyright © 2002-2003 Marco Tabini & Associates,
Inc. — All Rights Reserved
I
could not be happier right now. As I sit here at
my laptop, writing this editorial, by my side sits
a glass of beer that I made from scratch, not quite
a month ago. I’m inspired by the similarities that
exist between the evolution of php|architect as a
powerhouse publication and de facto standard

source of PHP knowledge, and the creation of
what is now a simple glass of lovely ale.
I brew with real grain and real hops. None of
this ‘just add water’ stuff. I’ve never done it, and I
won’t. I suppose it’s fine if you just want a ‘quick
and dirty’ beer. However, I have an overwhelming
feeling that my integrity as a brewer would be sac-
rificed for ‘ease’ (I call it ‘laziness’), and it doesn’t
sit well with me. I want honest beer. I want to
know how the wort was produced, and where it
came from. Indeed, I want to be intimately associ-
ated with the very essence of the finished product.
For better, or for worse.
I found this same spirit in the publisher of
php|architect, who I’ve now come to know as
both a good friend and close business associate,
Marco Tabini. Marco understood my leanings
toward things that were, for lack of a better term,
‘organic’ or ‘untainted’. I wanted material written
by doers. I shunned several articles by profession-
al writers whose writing lacked the spirit that
we’ve by now become accustomed to at
php|architect; the spirit of someone who has
fought and lost battles on their way to great dis-
coveries using PHP. Other writers, in comparison,
appear to have ‘just added water’. We’ve made it
a goal to avoid such articles. Of course, it is the
‘road less traveled’, but we feel it has made all the
difference, and you’ve let us know that we’re
right.

Of course, brewing from scratch comes with its
headaches. Brewing from scratch means more
steps are involved, the materials are handled and
transferred more often, and more opportunities
exist for molds and bacterias to be introduced into
the beer. While I’ve so far been able to avoid that,
and produce very drinkable beer, it is not without
its flaws. The one I’m drinking now took on a bit
of a ‘chill haze’ after being bottled, for example; a
minor problem that doesn’t affect anything but
the aesthetic qualities of the beer. As I continue to
brew and master the craft, I’ll inevitably fix the
‘chill haze’ problem, while introducing others.
Eventually, it all works out, and you achieve ‘excel-
lent beer’.
EDITORIAL
6
August 2003 · PHP Architect · www.phparch.com
Such is the case with this magazine as well.
We’re not perfect. We haven’t ever claimed to be
perfect, and as a team, I don’t think any of us
could ever foresee a day when there isn’t at least
the slightest bit of ‘haze’. However, it is the atti-
tude of this team that as long as there is not per-
fection, there is work to be done, and so we’re
constantly busy, if not with fingers to the key-
board, then with developing ideas or analyzing
weaknesses. It is this attitude, and the fact that it
permeates every digital thread of the publication,
that will earn us whatever critical acclaim may

await us.
Finally, beer and brewing is a learning process. I
was fortunate enough that my buddy Matt was an
already experienced brewer without a convenient
location to brew, and I was a homeowner with a
large back yard and a willingness to learn. Matt
and I have known each other since childhood, and
we work well together. We understand each other
and relate to each other better than most other
people we know. This makes for a great working
relationship, partially because we grew out of the
‘polite friendship’ stage somewhere around age
14. We constantly question and debate. Our beer
thus far has been better for it. This type of work-
ing relationship is invaluable in creating anything
of any quality.
In striving for quality of material in php|archi-
tect, anyone who has written for our editorial
team will note that I take a decidedly different
approach. The approach is largely the brainchild
of Marco and I, who have somehow been able to
achieve a vigorous and successful working rela-
tionship. Constantly questioning and debating
each other, we’re always playing ‘devil’s advocate’
to insure that, in the end, we’ve done right by all
parties involved. In the process we’ve learned
what makes this monster we’ve created tick, and
how to channel our efforts to add even more value
to our readership. Our ability to come to a ‘meet-
ing of the minds’ on all aspects of the publication

has brought us not only to where we are now, but
will influence the direction of the publication in
the future – for better, or for worse. In reality, at
the end of the day, it’s our ability to tell each other
that our ideas completely suck that has made all
the difference!
But there is another ingredient in our recipe at
php|architect. It’s the ‘recognition’ phase.
Recognition of a person’s ‘highest and best use’.
We seek people to join our team who we feel we
can work with, and we eventually move everyone
into a position where their interests and skills are
put to work to produce the best ‘stuff’ that they
can. As I’ve mentioned from the very beginning,
editorial work is not my highest and best use. No
matter how much I love editing and the editorial
process, the reality is that a) I’m not a hardcore
coder, and b) I’m not a hardcore editor!
It is with these words that I am proud to pass the
Editor in Chief torch to the very capable Peter
James. Peter has accomplished much in his rela-
tively short time as Senior Editor at php|architect,
affecting both the outward appearance of the
magazine, as well as the backend procedures for
coordinating the editorial process. All by his own
initiative, and all without a thought for anything
but the good of the publication. Furthermore, as if
this weren’t enough, he still constantly asks for
more responsibility, and a greater role in the mag-
azine’s creation. Finally, I came to the conclusion

that the only way for Pete to do anything more
was to take my job, which would allow me to be
applied to my highest and best use as well. So
from now on, it will be Pete’s job to try hard to
give you all a reason to read the editorial column
that I’m still convinced is a pretentious waste of
paper (be it digital or ‘dead tree’ in form).
I’ll not be far, mind you! I’m taking on a new role
that will also produce some really cool and excit-
ing new (but as yet unmentionable) ‘stuff’ in the
not too distant future. I’m excited at the opportu-
nity, though I’ll always make myself available on
those sleepless nights when Pete can’t get some
‘damned Linux code’ to validate or something.
I wish Pete a lot of luck, and thank him for the
hard work he’s done, along with the rest of the
production crew who have helped php|architect
become what we are today, and what we will be
tomorrow. I also thank all of the readers for the
feedback and guidance along the way.
until we meet again
brian.
7
PHP 4.3.3 RC3
PHP.net announced the release
of PHP 4.3.2 release candidate
3.
“This should be the last
release candidate prior to the final 4.3.3 release. Please
test this release as much as possible, so that any remain-

ing issues can be uncovered and resolved.”
Bug fixes include:
• escapeshellcmd()
can now handle quoted
arguments
• exit code lost when exit()
called from
register_shutdown_function()
• methods misidentified as constructors
• and much more
Visit php.net
to download or view the change log.
Apache 2.0.47
The Apache Software Foundation and the Apache HTTP
Server Project announce the tenth public release of the
Apache 2.0 HTTP Server.
This is a security, bug fix and minor upgrade release.
Due to security issues, any sites using Apache 2 versions
prior to Apache 2.0.47 should upgrade to Apache 2.0.47.
Security issues:
a. Fixed a bug in the handling of accept errors
by the prefork MPM when handling accept
errors, which could allow a denial of service
attack if multiple listeners are configured.
b. Fixed a bug in the optional renegotiation
code in mod_ssl which could cause cipher
suite restrictions to be ignored if optional
renegotiation is enabled.
c. Fix of denial of service attack in mod_proxy’s
handling of DNS results.

New features:
Added support for a “prefer-language” environment
variable to mod_negotiation”
To download, visit Apache.org
ionCube and the Cerberus
Encoder
ionCube.com announced the release of the ionCube
3.0.
The ionCube standalone PHP encoder is a high perform-
ance encoding solution for PHP, offering encoding of com-
piled code to deliver the maximum security and run-time
performance for encoded file, and features to allow easy
integration into build and release systems, and also web-
sites for just-in-time software delivery.
New Version 3.0 advantages:
a. Customizing of Loader event messages
b. Restricting encoded files to only cooperate
with other encoded files that have certain
‘properties’.
c. Improved encoding performance.
In addition to Version 3.0, Ioncube has released the
Cerberus Encoder.
This is the same as the full featured encoder, but adds
the ability to restrict files to a MAC address.
For more information, visit ionCube.com
.
NN EE WW SS TT UU FF FF
August 2003 · PHP Architect · www.phparch.com
WWhhaatt’’ss NNeeww!!
3 php|Cruise ‘04

10 Transforming XML to PDF with LaTeX
16 Ming & PHP
33 Sockets: Part 2
41 Grokking cURL
48 Maintenance from The Outset
57 Embedding Assembler in PHP
7 What’s New!
26 Granted!
29 Datanamic DeZign for Databases 3
65 Tips & Tricks
69 Bits & Pieces
71 e x i t ( 0 ) ;
NEW STUFF
PHPNuke 6.7
PHPNuke.org announced the release of version 6.7.
PHPNuke is a PHP based content management system.
This newest version fixes XSS and other vulnerabilities
and security bugs like path disclosure, and adds associat-
ed topics to the News module. There are many cosmetic
changes and minor bugs fixed, and the Update folder was
reorganized.
You can get more information or download from
PHPNuke.org
.
PHPEdit 0.7.1.131
PHPEdit.net announced the release of PHPEdit
0.7.1.131.
It’s still a development version but takes one step
further to the stable release. It contains proposal #2,
#3 and #7 of the PHPEdit Community.

PHPEdit
invites all users to report problems or tweaks
in 0.7.1.131 to the PHPEdit Community.
PHPEdit also asks all users to vote for requests they
want to be in the next release to the Community.
Visit PHPEdit.net
to download.
patUser 2.1.2 and 2.20
Beta
PHP Application Tools announced the release of
patUser 2.1.2 and 2.20 Beta
New in this version: bugs, notices and warnings
removed. Warning: this is the last version of patUser sup-
porting patDbc, as we are switching to PEAR::DB. Version
2.2.0 is the new branch supporting PEAR:DB - but keep in
mind that it is still BETA! If you are willing to test it, feel
free to send your bug reports to gERD directly. “
For more information or to download, visit
PHP-T
ools.de.
Databases
MySQL and PostgreSQL both announced new releases
this month.
PostgreSQL 7.3.4
PostgreSQL.org announced the release of their latest
version 7.3.4. This version addressed a potentially seri-
ous (although rare) server startup failure that was
recently reported. This release is critical for users of
PostgreSQL version 7.3.3, and highly recommended
for all other PostgreSQL users. The latest version can be

downloaded from the PostgreSQL FTP site
.
MySQL 4.0.14
MySQL.com announces the release of version 4.0.14.
This release is a maintenance release for the current
production version and includes functionality such as:
a. Enabled `INSERT’ from `SELECT’ when the
table into which the records are inserted is
also a table listed in the `SELECT’.
b. Changed optimiser slightly to prefer index
lookups over full table scans.
c. `FLUSH LOGS’ now rotates relay logs in addi-
tion to the other types of logs it already
rotated.
For the full list of additions and bug fixes, or to down-
load, visit MySQL.com
.
8
August 2003 · PHP Architect · www.phparch.com
php|a

10
August 2003 · PHP Architect · www.phparch.com
Types of documents
XML is commonly used to store several types of infor-
mation. Not only do developers use it in their daily
work to store configurations or define protocols, it is
also a great way to structure your everyday documents,
like letters, books, or articles. Even if they can be read
with any text editor (XML is an ASCII format), XML doc-

uments are not the first choice when it comes to docu-
ments that you'd like to read in your free time. The mix-
ture of tags, attributes and plain text may confuse you
while you are trying to get to the actual information.
XML was designed to be read by machines, not
humans. XML does not contain any layout but only the
structure of the raw data or content. An XML docu-
ment consists of several tags (like HTML) which
describe the information contained within the tags.
Any program may use these tags to decide what to do
with the text information between these tags. This
could mean a program is able to prioritize parts of a
document, if it had to create a search index or some-
thing similar.
Humans tend to decide what to do with the informa-
tion they read according to how it has been laid out. If
you are reading an article, you will surely recognize that
the headline has some significance in the context of the
rest of the article, as it is printed in bold and large let-
ters.
So if information has to be accessed by computers
and humans, the best solution would be to present
both species the same information in different formats.
The first choice of delivering information to a machine
is nowadays XML, while PDF can be read with almost
every client and operating system, and can easily be
printed, which enables you to take the information to
wherever you'd like without the need for a computer.
As we're living in the age of automation, you will not
want to create both versions of the information on your

own but use your friendly neighbourhood webserver
and scripting language (PHP) for it. This article will
explain one way to achieve this without a single drop
of sweat
Transforming documents
To automate the generation of one version of the two
required documents, you have to define which version
should be created manually and which one should be
generated by an application. This problem is solved in
the blink of an eye, as the previous section explained
Transforming XML to PDF
with LaTeX
By Stephan Schmidt
PHP Version: 4.x and above
O/S: Linux
Additional Software: LaTex
Code Directory: N/A
REQUIREMENTS
FF EE AA TT UU RR EE
FEATURES
11
August 2003 · PHP Architect · www.phparch.com
Transforming XML to PDF with LaTeX
that XML can be read by machines, and if your web-
server does not differ too much from the one we used,
it definitely is a machine. So once we have made the
decision to transform the XML document into a PDF
document, we have to stop for a moment and think
about how this transformation can be achieved.
After choosing PHP as a programming language (as

this is a article about PHP, after all) we realize that the
task of distributing and accessing the document is now
simpler, as both versions can later be accessed from
anywhere in the world from our web server over the
internet.
If you are familiar with transforming XML documents
you will probably be sitting at your desk yelling "Why
the $@#! aren't you using XSLT? It was designed specif-
ically for the task of transforming XML documents!".
The answer is quite simple: XSLT was designed to trans-
form an XML document to another XML document
with a different structure. A PDF is not an XML applica-
tion, and it is not even based on the ASCII standard.
This means you will have a hard time transforming XML
to PDF using XSLT. Some of you may still be sitting
there wondering why we are not using XSL-FO, which
is able to create PDF files and uses XML as its input for-
mat. We do not want to use XSL-FO as it is not very
easy to use. Furthermore, it has already been discussed
in other articles, and we are here to teach you some-
thing new. Call it an 'alternative method'. A better way
to transform XML to PDF is to take a detour and use
LaTeX. It is based on the ASCII character set, available
on nearly every operating system for free and can easi-
ly be converted to PDF documents (or other printable
formats).
A short introduction to
LaTeX
LaTeX is a document preparation system for high-qual-
ity typesetting. It is most often used for medium-to-

large technical or scientific documents, but it can be
used for almost any form of publishing. LaTeX is not a
word processor! Instead, LaTeX encourages authors not
to worry too much about the appearance of their doc-
uments, but to concentrate on getting the right con-
tent. This means LaTeX is not edited in a WYSIWYG
(What You See Is What You Get) editor. LaTeX docu-
ments can be created using your favourite editor,
whether it is vi, emacs, Homesite or even Notepad (but
not FrontPage).
This also means that LaTeX documents can be creat-
ed by any application that is able to create text files
(and of course PHP is able to do this). If you want to
view a LaTeX document, it has to be converted first.
You cannot view it directly in your editor, or you will get
the plain source code of your document, not the ver-
sion including layout. This would be similar to trying to
view an HTML document in vi or Notepad.
LaTeX is based on Donald E.Knuth's TeX typesetting
language. Development started in 1985 by Leslie
Lamport and is currently maintained by the LaTeX3
Project .
A typical LaTeX document looks like this
If you are familiar with markup or programming lan-
guages, you may already have guessed that this means:
1. The document is an article.
2. The title of the document is "Dynamic trans-
formations of XML to PDF with LaTeX".
3. The article has been written by Stephan
Schmidt ("Hey, that's me! Look mum, I'm on

TV!")
4. It has been written in April 2003.
5. The document consists of a title, followed by
the text "We love XML, but everyone wants
PDF."
As there are a lot of tutorials on LaTeX available on
the web (see the end of this article for useful links), we
will only list the most important features and show
some simple examples. LaTeX provides features for:
• Typesetting articles, technical reports, letters,
books and slide presentations
• Control over large (and we really mean large)
documents
• Control over sectioning, cross references, foot-
note, tables and figures
• Automatic creation of bibliographies and
indexes
• Inclusion of images
• Using PostScript or Metafont fonts
Basic usage of LaTeX
LaTeX documents consist of commands, macros and
environments as well as plain text. Commands always
start with a backslash ("\"). If a command needs param-
eters, they have to be enclosed in curly braces ("{" and
"}"), and if those parameters are optional, they have to
\documentclass{article}
\title{Dynamic transformations of XML to PDF with
LaTex}
\author{Stephan Schmidt}
\date{April 2003}

\begin{document}
\maketitle
We love XML, but everyone wants PDF.
\end{document}
FFEEAATTUURREESS
12
August 2003 · PHP Architect · www.phparch.com
Transforming XML to PDF with LaTeX
be enclosed in brackets ("[" and "]") and separated with
commas (","). Typical LaTeX commands look like this:
It is possible to include comments in your docu-
ments, they have to start with "%" and end at the end
of the line (like "//" in PHP).
Environments are used to split the document into
logical parts (like tags split XML documents).
Environments always start with the "\begin" command
and end with the "\end" command.
Now you know enough to start creating your very
own LaTeX document, and we will guide you through
the needed steps. Each document has to start with the
"\documentclass" command, which is being used to
define what kind of document you are creating. The
documentclass is responsible for the command set that
is available in your document. E.g. if you are writing an
article, there is no use for the "\chapter" command.
Furthermore the "\documentclass" command is used
to define the basic layout style, like two column layout
or paper format.
After this command you may load packages contain-
ing macro definitions using the "\usepackage" com-

mand. Packages include features for localization (differ-
ent character sets), hyphenation, graphics or cross ref-
erences.
Usually you will now include meta information about
the document, like the title, author or the date it has
been created. Finally the "\begin{document}" com-
mand is used to indicate the start of the actual docu-
ment.
Within the "document" environment you may use
any LaTeX command that is used to structure the doc-
ument or include graphics. Common commands
include:
• \section, \subsection and \subsubsection to
structure the document
• \em to emphasize parts of the document
• \item to create lists
• \footnote (for footnotes, of course)
• \label, \bibitem, \ref and \href to create
cross-references
• \includegraphics to include images
• \begin{table}, \begin{itemize} to create com-
monly used environments
• \tableofcontents, \listoftables and \listoffig-
ures to create indexes
• and many more
So your first LaTeX document could look like this:
OK, you have created your first LaTeX document,
containing the tragedy of your life, but nobody is able
to read it. What you probably want to do is to create a
PDF document from it, print it and distribute it through

your local comic book store. The next section will show
you how.
Converting LaTeX to PDF
Converting LaTeX documents to PDF is not something
you do every day, but nevertheless it is quite easy,
assuming you have the right software installed.
Otherwise you have to install it first.
If you are using Linux, there is no problem at all.
LaTeX is included in most distributions, and, if not, it is
available as an installable package for your favourite
package manager. The package is most often called
"tetex". You will find more information on the teTeX
homepage.
If you are a Windows user, you should download and
install MikTeX. This should pose no problem, as MikTeX
is distributed as a Windows installer.
Now, as you are proud to have LaTeX installed on
your system, there is nothing to hold you back from
generating the PDF version of your document. All you
\documentclass[a4paper,twocolumn]{article}
\usepackage{german} % support for German umlaut
\usepackage{hyperref}
\title{Me and the superheroes}
\author{Me, of course}
\date{\today}
\begin{document}
\maketitle
\tableofcontents
\section{My relationship to Superman}
\subsection{How it started}

When I was twelve, Superman was my greatest hero.
\subsection{Our relationship grew stronger}
I first met him in person at the age of 16.
\subsection{Everything has to end}
When he died at the hands of {\em Doomsday}, I was
really sad and devoted my life to Batman.
\section{My relationship to Batman}
My relationship to Batman started last week so
there's not much to tell, yet.
But I already know some of his friends:
\begin{itemize}
\item{\em Robin}, the Boy Wonder
\item{\em Oracle}, the former Batgirl
\end{itemize}
\end{document}
\begin{document}
% Place anything that is part of the document here
\end{document}
\documentclass{article} % This will be an article
% This line is a comment and will be ignored later
\maketitle
\footnote{I am a footnote}
\documentclass[a4paper,twoside]{book}
FEATURES
13
August 2003 · PHP Architect · www.phparch.com
Transforming XML to PDF with LaTeX
need to do is to call pdflatex with the filename of your
LaTeX document:
This creates several files in the folder where you have

saved your LaTeX document:
• superheroes.pdf is the PDF file you wanted to
create
• superheroes.log is a log file containing all log
messages
• superheroes.toc contains the table of con-
tents
• superheroes.out contains bookmarks for the
PDF reader
• superheroes.aux contains all data needed for
cross references
If you execute pdflatex, the
application parses the LaTeX
document from top to bottom
and generates the table of con-
tents, anchor files for hyperlinks,
PDF bookmarks and other meta
information. As this data should
also be included in the PDF file,
you have to call "pdflatex super-
heroes.tex" twice to achive the
desired result.
If you have done this, open
the file superheroes.pdf with
Acrobat Reader and you should
see your lifestory rendered as a
PDF document. If everything
went like it should, you will
probably see something like
what’s shown in Figure 1.

To get acquainted with LaTeX,
visit a tutorial on the web and
try fooling around with various
LaTeX commands and how they
are rendered as PDF.
Dynamic creation
of LaTeX and
PDF documents
You may wonder why this article
has been published in a maga-
zine about PHP, and there has
not been any PHP code so far.
This will change with this sec-
tion, where you will learn to
generate LaTeX documents
dynamically. As LaTeX docu-
ments consist of plain text, you may use any PHP func-
tion to modfiy them. The easiest way is to dynamically
create a LaTeX document using "echo" statements like
it has been done with HTML for ages, capture the result
and transform it to PDF. The following snippet shows
how it is done:
Now open your favourite webbrowser (Mozilla, I
hope), open the script and append your name as GET
parameter "name".
The URL will probably look like
http://localhost/latex.php?name=Aquaman. If you view
the sourcecode of the resulting page, you should see
the complete LaTeX source including the name you
entered in the URL. Save it to disk and transform it with

pdflatex.
\documentclass{article}
\begin{document}
Hi, my name is <?PHP echo $_GET["name"]; ?>.
\end{document}
pdflatex superheroes.tex
Figure 1: Your first PDF
FFEEAATTUURREESS
14
August 2003 · PHP Architect · www.phparch.com
Transforming XML to PDF with LaTeX
Of course this is not what we initially wanted to do,
as you still have to save the LaTeX document and trans-
form it manually. To automate the process of saving the
file to disk you should use PHP's output control and file
system functions. To automate the "pdflatex" call you
can use "system" or "exec". These functions are used to
execute any command that is available on your server,
just like you would execute it in the shell.
Using "echo" to dynamically create LaTeX documents
is the easiest - but also the ugliest - way to complete the
task. If you are using LaTeX to create a printable invoice
for customers in your online shop, you have to mix
LaTeX (which contains content like your address) with
PHP code (which is responsible for the logic of the
invoice). The resulting files will be very hard to main-
tain, if changes to either the logic our the layout have
to be made. This means you should use the same tools
that are nowadays commonly used for creating dynam-
ic HTML pages. Correct, we are talking of template

engines. Just use your favourite template engine (of
course, we recommend ours, patTemplate), create your
LaTeX templates and let PHP fill them with any content
you can to find. You may retrieve content from the user
by supplying forms, get it from databases, or even XML
files, which is the topic of the next section.
Transforming XML
documents using
patXMLRenderer
As the title of this article is "Transforming XML to PDF
with the help of LaTeX" we are now going back to
where we came from and take a look at XML docu-
ments and how they can be transformed to PDF. In
order to know how to transform LaTeX to XML we have
to take a look at the gap between XML and LaTeX doc-
uments. Both languages split the document into logical
expressions that can be nested as deep as you like. So
the easiest way to transform XML to LaTeX is to define
a LaTeX representation for each XML tag that is used in
your documents and parse the XML document recur-
sively. The result will be a LaTeX document with the
same structure and content as the source XML docu-
ment. As we do not wish to reinvent the wheel, we are
relying on an existing software package called
patXMLRenderer. There is online documentation for
this available at the official website.
This application makes use of a templateing engine
(patTemplate) and allows you to define a representa-
tion for each tag by creating a template with the same
name as the XML tag. In this template, you may access

the content of the tag and all of its attributes. As the
document is parsed recursively using a SAX based pars-
er, all children of a tag are transformed before the tag
itself is transformed. patXMLRenderer also allows you
to include dynamic content by overloading name-
spaces with methods of PHP classes. This enables you to
include content (SOAP requests, database content, text
files, ) while the XML file is being transformed to the
LaTeX document.
A sample XML file, that can be transformed to LaTeX
could look like this:
To transform this document to LaTeX (and later to
PDF) you have to define representations for all tags
used in the document: article, paragraph and imp. The
LaTeX templates could look like this:
The resulting LaTeX template will be:
Now all you have to do is to call "pdflatex" and the
XML file has been transformed to PDF and, as prom-
\documentclass[a4paper,twocolumn]{article}
\usepackage{german} % support for German umlaut
\usepackage{hyperref}
\title{Me and the superheroes, part 2}
\author{Me, of course}
\date{\today}
\begin{document}
\tableofcontents
\section{I lied to you}
When I was talking about {\em Superman}, I lied.
He came back from the dead and rose to the
glory

he once had.\\
\end{document}
<patTemplate:tmpl name="article">
\documentclass[a4paper,twocolumn]{article}
\usepackage{german} % support for German umlaut
\usepackage{hyperref}
\title{<{TITLE}>}
\author{Me, of course}
\date{\today}
\begin{document}
\tableofcontents
<{CONTENT}>
\end{document}
</patTemplate:tmpl>
<patTemplate name="paragraph">
\section{<{TITLE}>}
<{CONTENT}>\\
</patTemplate:tmpl>
<patTemplate:tmpl name="imp" whitespace="trim">
{\em <{CONTENT}>}
</patTemplate:tmpl>
<?xml version="1.0" standalone="yes"?>
<article title="Me and the superheroes, part 2">
<paragraph title="I lied to you">
When I was talking about <imp>Superman</imp>,
I lied.
He came back from the dead and rose to the
glory
he once had.
</paragraph>

</article>
FEATURES
15
August 2003 · PHP Architect · www.phparch.com
Transforming XML to PDF with LaTeX
ised, you did not lose one drop of sweat. We are cur-
rently developing an application that automates the
process of transforming XML to PDF and allows you to
combine several XML files through a graphical user
interface. It will hopefully be available as a download
together with patXMLRenderer from our website .
Common pitfalls
When transforming XML to PDF you have to be cau-
tious and avoid some common pitfalls. First of all, you
have to tell patTemplate that you want to create LaTeX
files instead of HTML files. This is done when creating a
new instance of the class, by passing "tex" as first
parameter to the constructor. When creating LaTeX
output, variables have to be enclosed in "<{" and "}>"
instead of just "{" and "}" so they cannot be mistaken for
LaTeX commands.
Furthermore, you have to replace some characters in
your XML files (quite similar to HTML entities). The
application that we are planning to release will do this
for you, so we'll just give a small overview of what has
to be done in the background:
• Some specialchars like "$", "{", "}", "_", etc.
have to be quoted by adding a preceding
backslash
• " " should be replaced by "\dots"

• \\ is used to mark the end of a paragraph,
remember to include it in your templates.
• ~ is used to explicitly create a space, similar to
&nbsp; in HTML
A list of all pitfalls would be nearly endless, given the
possible level of complexity of LaTeX and XML docu-
ments. If you experience problems with any special
characters you should take a look the LaTeX documen-
tation to see if the characters you used have any rele-
vance in LaTeX documents.
Stephan Schmidt is a web-application developer from Karlsruhe in
Germany. He started coding PHP about three years ago and decided to
join the Open Source community in 2001. He is a founding member of
PHP Application Tools (http://www
.php-tools.net) and author of
patTemplate, patXMLRenderer, patUser and other classes.
About The Author ?>
Click HERE To Discuss This Article
/>Useful Links
LaTeX Project: />patXMLRenderer: />patTemplate: />teTeX: />MikTeX:
PHP, mySQL and Curl Optimized for OSCommerce
Free Shared Certificate & Integrated SSL Server
20+ Contributions Pre-Installed on MS1 Release
Web Mail and Web Based File Manager
Full FTP and phpMyAdmin Access
Free Ongoing Hands-On Support
Web Stats by Urchin Reports
Free Installation and Configuration
USE PROMO CODE: phpa
Get an Extended Free Trial and Free Setup!

As the publishers of Ian's Loaded Snapshot we
know OSCommerce!
100's of OSCommerce powered sites rely on our
years of experience with OSCommerce, direct
866-994-7377 or
www.chainreactionweb.com
www.chainreactionweb.com/reseller.
As the publishers of Ian's Loaded Snapshot we
know OSCommerce!
100's of OSCommerce powered sites rely on our
years of experience with OSCommerce, direct
866-994-7377 or
www.chainreactionweb.com
www.chainreactionweb.com/reseller.
Nobody
Hosts OSCommerce Better!
We Guarantee It!
16
August 2003 · PHP Architect · www.phparch.com
T
he other day, while I was perusing through some
books at a local bookstore (computer books of
course), I noticed a book in the computer section about
Ming. "Ming", I said to myself, "never heard of that".
So I began to leaf through the book and discovered
that Ming is a library of code with a set of wrappers that
one can use to dynamically create .SWF format files
(compiled Flash Movies) using PHP. "Oh, this is too
cool", I can remember saying; however, since I had
already blown my book budget on some others, the

Ming book went back on the shelf. I did promise
myself, however, to look into this Ming library a little bit
more once I returned home. So I turned to the Internet
(a fantastic invention, this Internet thing), and found
plenty of documentation and examples to get my cra-
nial juices flowing.
I've finished my journey into cyberspace to seek out
Ming, and I'd like to share with you my findings. Don't
worry there won't be a three hour slideshow.
Let's take a little journey into the world of Ming with
PHP
The first stop is to investigate the website for the
Ming library, and this site is located at
r
ceforge.net. Take the time to visit the
site and scour through the function reference. There is
a nice list here, and using these classes and their meth-
ods we can do just about everything you can do with-
in the Flash authoring environment. You can even add
Actionscript, which is the built-in scripting language
inside Flash.
I think this library is great, and a lot of nice work has
been done here. My one beef is they could have
named the objects better to represent the Flash "lingo".
For instance, in Flash you would refer to an animated
object as a "movie clip", but the Ming project leaders
decided to call the class SWFSprite
. A small thing,
but nonetheless for a PHP developer beginning to learn
Flash and Actionscript, this could be confusing when

trying to get references and examples from the Flash
community.
Also check out the mailing lists archive located at
http://www
.opaque.net/pipermail/ming-fun/. If you are
having a problem, chances are good that someone else
has had the same problem, and there may be a work
around or a solution there.
Did you ever have to make up your
mind?
There are some cases where it makes sense to use the
Flash authoring environment, and there are some cases
where it would be nice to dynamically build a Flash
movie. As we work through some examples you will
begin to see that if you have an elaborate idea it may
be best to draw it in Flash, especially if your idea con-
tains plenty of animations. Even if you were to get
By Seth Wilson
PHP Version: 4.1.1+
O/S: Any
Additional Software: A browser with Flash Player
installed, Ming 0.2a library, MySQL
Code Directory: ming
REQUIREMENTS
MMiinngg && PPHHPP
FF EE AA TT UU RR EE
FEATURES
17
August 2003 · PHP Architect · www.phparch.com
Ming and PHP

fancy and really optimize the PHP code, coding a Flash
movie is a lot of work. Even still, I can think of a few
applications where a dynamically generated .SWF file
would be far easier to code than to draw.
A couple of cool applications I can think of would
work great for a website that offers advertising space.
For a basic advertising package you could create a PHP
web application where companies wishing to create a
web banner can pick from a set of pre-coded Flash
movies, and they include their own text and graphics.
That way they can advertise without going through a
lengthy design and development phase just for a sim-
ple web banner. Heck, they don't even have to know
Flash. You could also have a dynamically created photo
gallery or slideshow based on a user's query, and add
some neat fade in/fade out or other effects. Or you
could create custom e-cards where the content is deliv-
ered all in Flash. Actually, that's a great idea. Nobody
else use that idea, ok?
Make sure you check out a method in the SWFMovie
class called streamMP3(). This one caught my atten-
tion immediately. I figured what's a better example
than to make a Ming MP3 player, but first we need to
learn some fundamentals.
Ming compiles your PHP code into Flash version 4
movies, and at the same time any Actionscript you
embed is compiled to Flash version 5. Why that is I
don't know, so if you are looking to add Actionscript,
please remember it must conform to Flash 5
Actionscript syntax, which is slightly different than the

newest version, Flash MX. The very latest CVS Ming
version 0.3a has support for Flash MX. However, this
version is not released yet, so this article will focus on
Ming 0.2a.
If you do not presently have a browser with Flash
player 6 you will need to download
and install it. Flash player 6 is avail-
able from Macromedia's website
(http://www
.macromedia.com) and is
backwards compatible, so even
though Ming creates Flash 4 movies,
they will still be viewable with Flash
player 6.
Installation
The installation on a Windows
machine is fairly straightforward as
long as you are using a recent build
for Windows. I am running PHP
4.3.1 on a Windows 2000 machine,
and the Ming extension has already
been compiled into PHP. All we need
to do is enable Ming by modifying
the php.ini file. Locate and open the
php.ini file on your system and scroll
down until you find a section labeled
"Paths and Directories". There
should be a line just below this that begins with "exten-
sion_dir =". We want to change this line to reflect the
location of our PHP extension directory where a file

called php_ming.dll resides. If you have the default
install of PHP (c:\php) on a Windows box it will proba-
bly be
The second modification to the php.ini file is to
uncomment the line that reads
"
extension=php_ming.dll", under the section labeled
"Dynamic Extensions".
Installing Ming on a Linux system is a whole different
story. There are pre-compiled PHP modules on the
Ming website, but these are compiled for older versions
of PHP. That means you must build Ming support into
PHP yourself, unless you can find a nice soul who has
done the compiling for you. There is some documen-
tation on how to do this located at
r
ceforge.net.
After installation, restart your Apache server and -
badda bing - you are ready to roll. Of course, if you do
not want to cause yourself grief, make sure that Ming is
working properly by writing a little script as in Listing 1
and running it. If Ming is installed properly you should
be able to scroll down and see something similar to
Figure 1. If you still have problems check out your
Apache log file, it sometimes sheds some light on
things.
extension_dir = c:\php\extensions\
1 <?php
2 phpinfo();
3 ?>

Listing 1
Figure 1
FFEEAATTUURREESS
18
August 2003 · PHP Architect · www.phparch.com
Ming and PHP
Flash conventions
Before we get into using Ming and draw up some
movies, we should go over some conventions with
Flash. Flash movies have the origin of the movie at 0,0.
This point is in the uppermost left corner. From this
point the x value increases from the left to the right,
and the y increases as we go from top of the screen
downward. The other hot tip to know is that an
object's depth in the movie corresponds to the order
you added it to your movie. Have a look at Figure 2 to
see what I mean.
SWFMovie
The first object we should look at in the Ming library is
the SWFMovie
object. This is the object that handles
the creation of our movie, setting the frame rate, the
overall dimensions, the background colour, and also
handles the addition and removal of "items". These
items can be shapes, other movies, movie clips (or
sprites), buttons or text. If you want to see it (or hear
it), you must add it. Listing 2 shows the setup code
necessary for our movie. Don't bother viewing the
movie at this point because all you will see is a blank
white screen.

As you can see from Listing 2, I like to add the code
to instantiate the movie, and set all the settings right at
the beginning. Then I like to jump down to the bottom
and include two more lines to spit out the Flash movie
to the browser for viewing.
The first line will tell the browser what type of file this
is, and the next line outputs the finished .SWF file to the
browser. Alternatively, you can output the Flash movie
to a SWF file by using
SWF_Shape
Shapes are drawn using the SWFShape
object, and
shapes are the foundation to a Flash movie. You can
take a shape that is drawn and use it for background
fills, add it to a movie clip or sprite, or create a button
with it. At the same time we can fill this shape with a
colour, gradient or bitmap, as well. Enough talking
already! Let's draw our first shape (see Listing 3).
In this first example we are using a few methods of
the shape object. First off, we create a new SWFShape
$m->save($filename);
header('Content-type:
application/x-shockwave-flash');
$m->output();
1 <?php
2
3 $m = new SWFMovie();
4 $m->setDimension(320, 240);
5 $m->setBackground(255, 255, 255);
6

7 // All the rest goes in here!
8
9 header('Content-type:
10 application/x-shockwave-flash');
11 $m->output();
12
13 ?>
Listing 2
Figure 2
1 <?php
2 // create a new movie object
3 $m = new SWFMovie();
4 $m->setDimension(320, 240);
5 $m->setRate(12.0);
6
7 //Starting X and Y values
8 $x = 100;
9 $y = 100;
10
11 //Height of trangle
12 $height = 50;
13
14 // create a new Shape
15 $s = new SWFShape();
16
17 //Set the line width and colour
18 $s->setLine(2, 0, 200, 0);
19
20 // create a new Fill red, green, blue and
alpha

21 $f=$s->addFill(0,255,0,255);
22
23 // set the fill to the new fill just
created
24 $s->setRightFill($f);
25
26 // Start drawing the Shape
27 $s->movePenTo($x, $y);
28 $s->drawLineTo($x-(0.5*$height),$y+$height);
29 $s->drawLineTo($x+(0.5*$height),$y+$height);
30 $s->drawLineTo($x, $y);
31
32 // add it to the movie
33 $m->add($s);
34 $m->nextFrame();
35
36 // and output
37 header('Content-type:
application/x-shockwave-flash');
38 $m->output();
39 ?>
Listing 3
FEATURES
19
August 2003 · PHP Architect · www.phparch.com
Ming and PHP
object, which in this case we are calling $s. Then we
use the setLine() method to set the line thickness
(the first argument) and the colour (the last three argu-
ments - red, green and blue). In this case, we specify a

dark green. The line
adds a light green fill (the first three arguments) to
the outline we are about to draw. The last argument to
addFill() is the "alpha" of the fill. Alpha can be best
explained as the opaqueness of the fill, with 0 being
transparent and 255 being fully opaque. The
setRightFill() and setLeftFill() methods are
best explained in the Ming documentation.
Now that we've told Ming what we want to draw, we
can now give the commands to draw. The best way to
visualize this is to think about actually drawing on
paper by hand. First you move your pen to a spot, put
it down on the paper then draw a line to another point.
This is the exact same process used by the
movePenTo() and drawLineTo() methods.
One note that I should mention here is when you are
coding any Ming project, step by step is the best plan
of attack. Make sure that you have display_errors on
and, as a rule of thumb, don't put your head down and
bang out three hours of code, because you'll spend the
same amount of time, or more, debugging.
If you run Listing 3 in your browser, you should see
something similar to Figure 3.
SWFGradient
Instead of a straight colour fill, you can also fill a shape
with a gradient using the SWFGradient
object. A gra-
dient is basically a smooth transition from one colour to
another. There are two types of gradients: a linear gra-
dient, which is a line; and a radial gradient, which is cir-

cular. Listing 4 shows a basic gradient fill. The code is
setup to show the linear gradient first. Just comment
out the first line calling addFill() and uncomment
the line below it to see the radial gradient. Make sure
you run the script in your browser to have a look at
what it does.
$f=$s->addFill(0,255,0,255);
Figure 3
FFEEAATTUURREESS
20
August 2003 · PHP Architect · www.phparch.com
Ming and PHP
SWFButton
Buttons in Flash act as a user interface with the movie.
You create a button with Ming by using the
SWFButton
object. A button is basically a specialized
movie clip. Once you create the
object, you can add previously-drawn
shapes to define the shape and size of
the button. Without a shape, a but-
ton will not be seen by your users. A
basic button has up, down, over, and
hit states, and you can define differ-
ent shapes for each button state to
create some neat effects.
One downfall with Ming is you can-
not add text or other shapes to your
button. You can work around this by
first drawing the button, then draw-

ing another shape over top. We will
use this technique in our MP3
player.
Have a look at Listing 5 (included in this month’s
package), and then run this script in your browser to
see the button in action. You can tell a shape is a but-
ton, because when you mouse over the button the
mouse icon will change from an arrow to a hyperlink
icon.
The future looks painful. Let's create a class.
drawShapes class
I hope you're starting to see that if you
have a movie with a bunch of buttons
and shapes, it will become very painful
to code. The last example has over fifty
lines just to draw the shapes for one
button. If you had even five buttons in
your movie, your code would look very
messy. We could create some functions
that will do some of the drawing, but
this is still cumbersome because you
either have a function with a huge
number of arguments, or it would real-
ly only save a couple of lines of code.
There is a solution to this problem:
another object, of course. I developed this class (shown
in listing 6 - also included in this month’s package) to
aid in the drawing of shapes. Feel free to add more
1 <?php
2 // create a new movie object

3 $m = new SWFMovie();
4 $m->setDimension(320, 240);
5 $m->setRate(12.0);
6
7
8 // create a new Shape
9 $s = new SWFShape();
10
11 //Set the line width and colour
12 $s->setLine(2, 0, 200, 0);
13
14 $g = new SWFGradient();
15 $g->addEntry(0.0, 0, 255, 0, 255);
16 $g->addEntry(1.0, 255, 255, 255, 0);
17
18 $f = $s->addFill($g, SWFFILL_LINEAR_GRADIENT ); // Comment this to see radial
19 //$f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT); // Uncomment this to see radial
20 $f->scaleTo(0.25);
21 $f->moveTo(100, 100);
22
23
24 // set the fill to the new fill just created
25 $s->setRightFill($f);
26
27 // Start drawing the Shape that defines the fill
28 $s->movePenTo(0, 0);
29
30 $s->drawLine(320, 0);
31 $s->drawLine(0, 240);
32 $s->drawLine(-320, 0);

33 $s->drawLine(0, -240);
34
35 // add it to the movie
36 $m->add($s);
37 $m->nextFrame();
38
39 // and output
40 header('Content-type: application/x -shockwave-flash');
41 $m->output();
42 ?>
Listing 4
“ don't put your
head down and
bang out three
hours of code,
because you'll
spend the same
amount of time, or
more, debugging."
FEATURES
21
August 2003 · PHP Architect · www.phparch.com
Ming and PHP
shapes as you like.
Have a look at Listing 7, which shows the previous
example, this time using the drawShapes object. That
looks a lot nicer, and is easier to follow. I think so, any-
way.
Animate…good times come on!!!
(Or is that celebrate?)

Everyone loves (or hates) Flash movies because of the
animations. With the Flash authoring tools, you have a
nice interface in which to draw your beginning and end
shapes in different frames on the timeline, after which
Flash will happily perform all the drawing in between.
Not the case with Ming. Now you are the person that
will happily draw all the animation in between. Really,
it's not that bad. If we use our wits, and some control
structures, we can minimize some of the work.
We can use the following methods to animate our
shapes.
• move(x,y) and moveTo(x,y)
• scale(x,y) and scaleTo(x,y)
• rotate(degrees) and
rotateTo(degrees)
• skewX(x), skewY(y), skewXTo(x),
skewYTo(y)
• and you can also transform colour
After looking at Listing 8 (included in this month’s
package), which shows some of the methods used to
animate our triangle, run the script to see the little guy
in action.
Also note that you must advance the
movieclip or movie frame-by-frame
manually using the nextFrame()
method. You can also fully animate
shapes using only Actionscript, but
that's beyond the scope of this article.
Let's build this MP3 play-
er

I think we have most of the tools now to
build a fully functional MP3 player, and
any other tools we will pick up on the
fly. I have told a little white lie, it's not
really an MP3 player, but rather the
player plays a SWF file with an embed-
ded MP3. Either way, the users listen-
ing will not be able to download the
track.
There are two parts to this player.
The first part will be a PHP script that
will allow a user to upload an MP3 file.
The second part is the user interface
that will have the play, stop and pause
buttons, volume control, and selectable
playlist.
Upload and add script
MP3 files will be uploaded and convert-
ed to a SWF file using a separate PHP
script from the player. The script, called
upload.php, uses a library developed
by someone else (no sense re-inventing
the wheel) that will read the MP3 head-
er information and the ID3 tag. The
header information is needed to grab
the length of the song. It is absolutely
imperative to retrieve this information
because when we embed the MP3 into
a SWF file we need to make sure the
1 <?php

2 // create a new movie object
3 $m = new SWFMovie();
4 $m->setDimension(320, 240);
5 $m->setRate(12.0);
6
7 //Starting X and Y values
8 $x = 40;
9 $y = 20;
10
11 //Height of trangle
12 $height = 50;
13
14 include("drawShapes.php" );
15
16 $test = new drawShapes();
17
18 $test->setShapeLineStyle(2, 0, 200, 0);
19 $test->setShapeFillStyle(0,255,0,255);
20
21 // make the first shape green
22 $b = new SWFButton();
23 $b->setUp($test->getTriangleShape ($x,$y,"up",$height));
24
25 // make it blue
26 $test->setShapeFillStyle(0,0,255,255);
27 $b->setOver($test->getTriangleShape($x,$y,"up",$height));
28
29 // make it blue a little alpha
30 $test->setShapeFillStyle(0,0,255,150);
31 $b->setDown($test->getTriangleShape($x,$y,"up",$height));

32
33 // make it blue a little alpha
34 $test->setShapeFillStyle(0,255,0,255);
35 $b->setHit($test->getTriangleShape ($x,$y,"up",$height));
36
37
38 //add the button to the movie
39 $i = $m->add($b);
40 $i->moveTo($x,$y);
41
42
43 $m->nextFrame();
44
45 // and output
46 header('Content-type: application/x-shockwave-flash');
47 $m->output();
48 ?>
Listing 7
FFEEAATTUURREESS
22
August 2003 · PHP Architect · www.phparch.com
SWF file has enough frames to encapsulate the entire
song. The ID3 tag information is stored into a MySQL
database and is used by the player to display track
information.
The HTML form is called addplaylist.html, and
is shown in Listing 9. It is the front end for the
upload.php script, shown in Listing 10 (included in
this month’s package).
We need to modify the php.ini file again to make

sure the file is uploaded and processed properly. Open
up your php.ini file and search for the line that reads
and change to something appropriate like
We also need to change the input and execution
times to accommodate the larger sized files. Change
these settings to
You may need to fiddle with these settings if you are
uploading files larger than 8 megs.
As I mentioned, the script that handles the process-
ing is called upload.php and can be seen in Listing
10. The script performs some basic validation of the
uploaded file, strips out the ID3 tag and stores that as
a new database record. It then processes the MP3 by
embedding it into an SWF file. The Ming library is used
for the last step, and the newly created SWF is saved to
the local disk. Make sure you have permissions set for
the directory to be able to write files, or you could
change the script slightly to suit your tastes. There are
a few variables in this script that you may have to
change to suit your system. The first variable is
$uploaddir. You will have to change this path to
reflect where your player script resides. The other vari-
ables that could be changed are $user and $pwd
which are used for accessing the MySQL database.
I have run into some problems uploading MP3 files
that have no ID3v1 information. I know this is a pain
but try and make sure there is ID3v1 information in the
MP3's you upload.
For those worried about security (and we all should
be), having any Regular Joe upload a MP3 file to their

server would keep them up at night. Think of this script
as an administration tool then, don't put it online, and
sleep well.
The player interface
(See the complete listing for the player in Listing 13, in
this month's package)
Let's make the interface look cool. I thought that
using a radial gradient that transitions from black to
white transparent, and placing the center of this gradi-
ent in the four corners of the rectangle shape would
look really neat. The only way to do this is to create
four identically sized shapes and place one gradient in
different corners. Run Listing 11 (also included in this
months package) in your browser to see the effect I've
been talking about.
Next up is to add some text fields. We will use three
text fields for our player. One text field will contain
information on which track is currently being played,
another will be a status bar and the last will serve the
max_execution_time = 90
max_input_time = 90
upload_max_filesize = 8M
upload_max_filesize = 2M
Ming and PHP
1 <!DOCTYPE HTML PUBLIC " -//W3C//DTD HTML 4.0 Transitional//EN">
2 <html>
3 <head>
4 <title>Add Song To Ming Mp3 Playlist</title>
5 <meta name="generator" content="editplus">
6 <meta name="author" content="">

7 <meta name="keywords" content=" ">
8 <meta name="description" content="">
9 </head>
10
11 <body>
12 <h3>Add Song To Ming Mp3 Playlist</h3>
13
14 <form enctype="multipart/form -data" action="listing10.php" method=post>
15
16 <! Max upload file size is 8MB >
17
18 <input type="hidden" name="MAX_FILE_SIZE" value="8388608" />
19 Add this MP3<input name="userfile" type="file" />
20 <input type="submit" value="Send MP3 File" />
21 </form>
22
23
24 </body>
25 </html>
26
Listing 9
FEATURES
23
August 2003 · PHP Architect · www.phparch.com
Ming and PHP
purpose of a scrolling playlist. I have not covered how
to add a text field, so I will do it now.
A text field cannot be animated but it can be dynam-
ically changed during the movie's timeframe. When
you instantiate the SWFTextfield object,

you can specify the behaviour of the text field by
specifying different flag arguments. The flags are listed
below from the Ming documentation. You can set mul-
tiple flags by using the bitwise OR operator ( | ).
Valid text field flags:
You can also specify the height, width, type and size
of the font using the methods of the SWFTextField
object. You can even specify the instance name of the
text field so that you may populate it dynamically using
Actionscript.
The status bar text field for our player will be named
"status", and will be the default, non-editable text field.
The second text field, which will contain track informa-
tion, will be named "trackinfo". The scrolling playlist
will be non-editable, non-selectable, multiline, and will
contain HTML code. This is an undocumented flag for
an SWFTextField
, called SWFTEXTFIELD_HTML, that
will make our text field render HTML code. We want to
render this text field as HTML so that each track will be
listed with a hyperlink which when clicked on will load
that song into the player. Once you see you see the
Actionscript it will make more sense.
Now we can add our buttons to play, pause, and
stop, as well as volume controls and scrolling buttons.
The buttons for track control will be circles, and the vol-
ume and scroll buttons will be triangles. The
drawShapes class comes in very handy. Have a look at
the listing to see the addition of the buttons. Let's
make our buttons a cool X-box green, with dark green

borders
With buttons, come actions
Of course, now that you have a button, you want to be
able to do something once the user clicks on it. You
can add Actionscript to a button, movie clip or the
movie itself. All actions are added using the
SWFAction
object.
You can add many Actionscript statements inside one
add SWFAction
command, just make sure to end each
Actionscript statement with a semi-colon.
It's very simple to add Actionscript to a button. The
SWFButton
object has a method called
addAction(), and the first argument we pass to this
method will be an SWFAction object complete with
the Actionscript. The second argument is a flag to tell
Flash after which button event this code should be
called.
$b->addAction(new SWFAction("_root.mp3.play();"),
SWFBUTTON_MOUSEUP);
SWFTEXTFIELD_NOEDIT
indicates that the field shouldn't
be user-editable
SWFTEXTFIELD_PASSWORD
obscures the data entry
SWFTEXTFIELD_DRAWBOX
draws the outline of the text field
SWFTEXTFIELD_MULTILINE

allows multiple lines
SWFTEXTFIELD_WORDWRAP
allows text to wrap
SWFTEXTFIELD_NOSELECT
makes the field non-selectable
$t = new SWFTextField([$flags]);
Have you had your
Have you had your
PHP today?
PHP today?
Visit us at
and subscribe today.
php|architect
• Subscribe to the PRINT edition
• Subscribe to the ELECTRONIC edition
FFEEAATTUURREESS
24
August 2003 · PHP Architect · www.phparch.com
Ming and PHP
For the volume controls, we have a few lines of
Actionscript. When the volume up or volume down
buttons are clicked the Actionscript global variable
called Vol will be incremented or decremented accord-
ingly, then a new Sound object will be created, and will
be passed this new volume setting.
The scroll up and scroll down buttons also have some
Actionscript code. They access a property of the text
field called 'scroll'. If the playlist has more items than
what can be seen in the text field, these buttons will
allow the user to scroll up or down to see more items.

This scrolling action is done by
incrementing or decrement-
ing the scroll property of the
text field.
Add some fancy
touches with
MySQL
We are going to also harness
the power of MySQL, and use
it to hold information about
the MP3. Ultimately, we are
using an SWF with an embed-
ded MP3 file, so we cannot
grab any information about
the MP3 unless it is stored
somewhere else. We are going to use the same data-
base to populate the scrolling playlist, and also to
retrieve information about the current track being
played. Listing 12 shows the SQL file to import the
table structure into a MySQL database. Let's call the
database "mp3stream", and import this information
into it.
Now, last but not least, we can now add a movie clip
or SWFSprite
that will act as a container for the MP3
embedded SWF file. Let's call this movie clip (sprite)
"mp3", and leave it empty for now because we are
going to add the MP3 dynamically using Actionscript
code.
Actionscript for the movie

There are only a few lines of Actionscript to get this
whole movie going (see the bottom of Listing 13). The
first thing we do is set the initial volume using the pre-
viously mentioned Vol Flash variable. Then we load the
SWF movie containing our MP3 using the loadMovie
function into the empty movie clip called "mp3". Next,
we create a new Sound object to handle the volume
initially. Lastly, we add the track information into the
textfield. That's it. We are ready to press play….so go
on, press play.
All of this code is neatly commented and can be seen
#
# Table structure for table `mp3info`
#
CREATE TABLE mp3info (
mp3ID int(11) NOT NULL auto_increment,
mp3Filename varchar(255) NOT NULL default '',
mp3Length int(11) NOT NULL default '0',
mp3Title varchar(255) NOT NULL default '',
mp3Artist varchar(255) NOT NULL default '',
mp3Album varchar(255) NOT NULL default '',
mp3Year varchar(10) NOT NULL default '',
mp3Comment varchar(255) NOT NULL default '',
mp3Genre varchar(255) NOT NULL default '',
PRIMARY KEY (mp3ID)
) TYPE=MyISAM;
Listing 12
<? Tap Internet PHP Training Courses ?>
Been handed a PHP project and don't quite know where to start? Itching to learn PHP in a classroom environment?
Tap Internet has trained hundreds of PHP developers over the past 2 years, and is the largest independent PHP training

organization in the U.S. We provide complete PHP training solutions for all levels, including on-site courses.
PHP Beginner- $999
Next class: Sept 22-24, 2003
A 3 day course providing beginners a solid
foundation in PHP.

Basic programming concepts

Dynamic HTML pages

Loops/control structures

Array handling

File system management
PHP Advanced - $1999
Next class: Sept 15-18, 2003
A full 4 days with all topics from PHP
Beginner plus:

Session management

Objects

PDF creation

Database usage

Security issues
LogiCreate - $1299

Next class: Sept 29-31, 2003
A 3 day course covering the LogiCreate
application server.

Installation

User management

Custom permission systems

Rapid application development

Error handling
All classes feature hands-on instruction with friendly experienced teachers. Each student is assigned an individual
workstation, and class sizes are limited to increase personal instruction. Lunch and snacks are also provided.
Call 1-866-745-3660 or 734-480-9961 to book your seat now or visit />“For those worried
about security,
having any
Regular Joe
upload a MP3 file
to their server
would keep them
up at night.”
FEATURES
25
August 2003 · PHP Architect · www.phparch.com
Ming and PHP
in Listing 13. The finished player can be seen in Figure
4.
How to make this better

To make this script a full blown application, we would
have to add a few touches to really make it polished. A
pre-loader would be essential to show users on slow
connections that the MP3 is loading. A Flash version
check would also be really slick. That way you can
direct users that do not have the Flash plug-in installed
to Macromedia's site. The ultimate touch would be a
Winamp-style visualizer with some cool animations that
would really make your CPU smoke.
You could change the architecture of this script a
small bit, and have the script embed the MP3 into the
SWF on-the-fly (rather than creating it up-front). This
would limit the size of media files on your server, but
will slow the performance of the script significantly.
A second step in the file upload procedure allowing
users to add or change the ID3 information before sav-
ing to the database would be nice feature, I think. Also
adding more shapes to the drawShapes object would
be nice. Hearts, stars, more geometric shapes like pen-
tagons, hexagons and the like would be really helpful,
as well.
So what is this script really good
for?
I think this script would be great for anyone who wants
to offer some audio content on their website. If you are
a motivational speaker or a local garage band, and you
don't want people to grab your content this might be
a solution for you. Since this player uses Flash, you are
going to reach nine out of ten Internet users without
them having to download a separate plug-in.

Acknowledgements
I would like to thank a regular contributor to the Ming
mailing list, Armel Grignon at mingshop.arpane.net
,
who indirectly, through his posts to previous queries,
helped me immensely. I would also like to thank the
author of the mp3.inc.php script. I searched high and
low for the author, but came up empty. Thanks for sav-
ing me some work!
Seth Wilson runs his own computer consulting business based in
Waterdown, Ontario, Canada. He enjoys breaking and fixing comput-
ers, writing code, playing, watching, and talking hockey and rollerblad-
ing with his wife Trish
About The Author ?>
Click HERE To Discuss This Article
/>Figure 4

×