Top Visited
Switchboard
Latest
Past week
Past month

PHP Bulletin

PHP as a General-Purpose Language

If PHP is your scripting language of choice when it comes to developing dynamic Web sites, you probably have grown to love its immediacy and power. An estimated ten million Web sites use at least some PHP scripting to generate their pages.

Although most people use PHP primarily as a Web development scripting system, it possesses all the characteristics of a proper general-purpose language that can be useful in a variety of other environments. In this article, I illustrate how it's possible to use the command-line version of PHP to perform complex shell operations, such as manipulating data files, reading and parsing remote XML documents and scheduling important tasks through cron.

The contents of this article are based on the latest version of PHP at the time of this writing, 4.3.0, which was released at the end of 2002. However, you should be able to use older versions of PHP 4 without many problems. I explain the differences you may encounter as necessary.

With the release of PHP 4.3, a new version of the interpreter called command-line interface (or PHP-CLI) is available. PHP-CLI is not a shell as the name implies but, rather, a version of PHP designed to run from the shell. As far as software development is concerned, only a few differences exist between PHP-CLI and its CGI or server API (SAPI) counterparts. For one thing, traditional Apache server variables are not available, as Apache isn't even in the picture, and the HTTP headers are not output when a script is executed. Also, the engine does not use output buffering, because it would be of no benefit in a non-Web environment.

PHP-CLI is created by default when you compile your version of PHP, unless you use the --disable-cli switch when you execute the configuration script. It is not, however, installed by default. But, you can force make to compile it and install it by using a special command:

	make install-cli

To verify whether the CLI version of PHP is installed on your server, all you need to do is execute this command:

	php -v

The resulting version information should specify whether the CLI or CGI version of PHP is being executed. If you have only the CGI version and don't want to install the CLI, you still can use PHP as a shell-scripting language. Their differences are mostly aesthetic, and their effect can be toned down somewhat by using the right command-line switches when invoking the interpreter.

Parsing an RSS Feed

Being a lover of weblogging, I routinely visit a certain number of blogs on the Net. This is a somewhat tedious process, because I don't like the idea of a news aggregator running on my machine on a continuous basis, and I do not see the need to pay for one. It seemed, though, that an RSS aggregator might be a great way to show how some of PHP's powerful features, such as the fopen() wrappers and the built-in XML parsing engine, could be used to create a script that runs from the command line.

An RSS feed is, essentially, a simple XML document that contains information about items published by a news source, such as Linux Journal. Its format consists of a channel container that includes several optional elements, such as a title and description, in addition to a set of item subcontainers. Each of these, in turn, contains a title, a description and a link to the news story it represents.

Typically, a news aggregator loads the information from an arbitrary number of news feeds and presents everything together in a given format, such as HTML. For users, a news aggregator represents a convenient way to create a single point of information for all the news sources of interest.

My PHP-based news aggregator, called Feeder and shown in Listing 1, presents its results in a plain-text e-mail that is sent to the user, who then executes the script. Feeder loads a list of RSS feeds from a file located in ~/.feeder.rc (Listing 2). The first line of this file also contains the e-mail address to which the news feed data should be sent. The content of the configuration files are loaded using a simple trick: the back-tick operator, which performs exactly the same function as it does in the shell, is used to call the cat command. The output is then split into an array of individual lines using the explode function.

Listing 1. Feeder, an RSS Aggregator

<?php

// Classes used internally to parse the XML
// data

class CItem
{
  var $title;
  var $description;
  var $url;
}

class CFeed
{
  var $title;
  var $url;

  var $items;

  var $currentitem;
}

// XML handlers

function ElementStarter($parser, $name, $attrs)
{
  global $currentelement;
  global $elements;

  $elements[$currentelement ++] = $name;
}

function ElementEnder($parser, $name)
{
  global $elements;
  global $currentelement;
  global $currentfeed;

  if ($name == 'ITEM')
  {
    $currentfeed->items[] =
           $currentfeed->currentitem;
    $currentfeed->currentitem = new CItem;
  }

  $currentelement--;
}

function DataHandler ($parser, $data)
{
  global $elements;
  global $currentelement;
  global $currentfeed;

  switch ($elements[$currentelement - 1])
  {
  case  'TITLE' :

      if ($elements[$currentelement - 2] == 'ITEM')
        $currentfeed->currentitem->title .= $data;
      else
        $currentfeed->title = $data;

    break;

  case  'LINK'  :

    if ($elements[$currentelement - 2] == 'ITEM')
      $currentfeed->currentitem->url .= $data;
    else
      $currentfeed->url .= $data;

    break;

  case 'DESCRIPTION'    :

    if ($elements[$currentelement - 2] == 'ITEM')
      $currentfeed->currentitem->description
                  .= $data;
    else
      $currentfeed->description .= $data;

    break;
  }
}

// Feed loading function

function get_feed ($location)
{
  global $elements;
  global $currentelement;
  global $currentfeed;

  $xml_parser = xml_parser_create();

  $elements = array();
  $currentelement = 0;
  $currentfeed = new CFeed;
  $currentfeed->currentitem = new CItem;

  xml_parser_set_option
    ($xml_parser, XML_OPTION_CASE_FOLDING, true);
  xml_set_element_handler
    ($xml_parser, "ElementStarter", "ElementEnder");
  xml_set_character_data_handler
    ($xml_parser, "DataHandler");

  if (!($fp = fopen($location, "r")))
    return 'Unable to open location';

  while ($data = fread($fp, 4096))
  {
    if (!xml_parse($xml_parser, $data, feof($fp)))
      return 'XML PARSE ERROR';
  }
  xml_parser_free($xml_parser);

  return $currentfeed;
}

// Feed formatting function

function format_feed ($feed, $url)
{

  if (!is_object ($feed))
  {
    $res = "Error loading feed at: $url.\n" .
           "$feed\n\n";
  }
  else
  {
    $res = "{$feed->title}\n[{$feed->url}]\n\n";

    foreach ($feed->items as $item)
    {
      $res .= "{$item->title}\n[{$item->url}]\n\n" .
        wordwrap ($item->description, 70) . "\n\n" .
        str_repeat ('-', 70) . "\n\n";
    }
  }

  return $res;
}

// Load up configuration file

$data = explode ("\n", trim (`cat ~/.feeder.rc`));

// The first line is the address, so skip it

$result = 0;

// Cycle through and get all the feeds

for ($i = 1; $i < count ($data); $i++)
  $result .= format_feed
    (get_feed ($data[$i]), $data[$i]);

// Mail them out to the user

mail ($data[0], 'Feeder update', $result);

?>

The parsing of the XML feed happens in two phases. First, the get_feed function uses the fopen() wrappers to download the feed in 4KB chunks. These are then passed on to an instance of the built-in PHP XML parser, which proceeds to interpret their contents and call ElementStarter(), ElementEnder() and DataHandler(), as needed. These three functions, in turn, parse the contents of the XML file and create a structure of CFeed and CItem instances that represents the feed itself. The script then calls the format_feed function, which scans feed objects and produces a textual version of their contents. Once all the feeds have been parsed and formatted, the resulting message is e-mailed to the intended recipient.

As a security note, format_feed() uses the wordwrap function to format the description of a news item so it doesn't span more than 70 columns. This helps enhance the readability of the news feed by presenting the user with a more compact look. Prior to PHP 4.3.0, the source code for wordwrap() included an unchecked data buffer that could, in theory, be exploited to execute arbitrary code, thus presenting a security issue. If you're not using the latest version of PHP, you probably should either avoid using wordwrap() or replace it with your home-grown version.

Executing the Script

The easiest way to execute a script from the shell is to invoke the PHP interpreter explicitly:

marcot ~# php feeder.php

If you have the CGI version of PHP, you may want to use the -q switch, which causes the interpreter to omit any HTTP headers that are normally required during a Web transaction.

This explicit method, however, is not very practical if you want your users to access the scripts you write conveniently. A better solution consists of making the scripts executable, so they can be invoked explicitly, as if they were autonomous programs. To do this, first determine the exact location of your PHP executable:

marcot ~# which php
/usr/local/bin/php

The next step consists of creating a shebang—an initial command that instructs the shell interpreter to pipe the remainder of an executable file through a specific application (the PHP engine in our case). The shebang must be the first line of your script—there can't be any white spaces before it. It starts with the character # and the character !, followed by the name of the executable through which the remainder of the file must be piped. For example, if you're using the CLI version of PHP, your shebang may look like this:

#!/usr/local/bin/php

If you're using the CGI version of the PHP interpreter, you also can pass additional options to it in order to keep it quiet and prevent the usual HTTP headers from being printed out:

#!/usr/local/bin/php -q

The final step consists of making your script executable:

marcot ~# chmod a+x feeder.php

At this stage, you can run the script without explicitly invoking the PHP interpreter; the shell will take care of that for you.

As you may have noticed, I have not renamed the script to remove the .php extension. Even though the extension itself is not necessary when running scripts from the shell, its presence makes it easy for text editors such as vim to recognize it and highlight the source's syntax:

marcot ~# ./feeder.php

 

Running PHP Scripts through Cron

A news aggregator that must be invoked explicitly every time you want to read your news page is not very useful. Therefore, you may want to have your system run it automatically on a specific schedule. The cron dæmon generally is used for this purpose. cron is a simple dæmon that runs in the background and, at fixed intervals, reads through a special file, called crontab, that contains schedule specifications for each of the users on the server. Based on the information contained in the crontab file, cron executes an arbitrary number of shell commands and, optionally, sends an e-mail notification of their results to the user. The crontab file contains entries in the following format:

minute hour
day month
weekday command

 

 

The first five fields indicate the time or times at which a command must be executed. For example:

5 9 13 9 1 /usr/bin/feeder.php

means that at 9:05 AM of September 13, the command /usr/bin/feeder.php will be executed, but only if September 13 falls on a Monday (weekday 1). This may sound complicated, but it's an extreme example. Most likely, you want to execute commands on a simpler schedule, like the beginning of every hour. This is accomplished by using the * wild card, which means any. So, for once an hour, on the hour, you would enter:

0 * * * * /usr/bin/feeder.php

And for once a day, at midnight, enter:

0 0 * * * /usr/bin/feeder.php

The time fields allow for even more complex specifications. For example, you can create a list of specific times by separating them with a comma:

0,30 * * * * /usr/bin/feeder.php

This crontab specification causes the command /usr/bin/feeder.php to be run every 30 minutes starting from the hour. Similarly, you can specify inclusive lists of times by separating them with a dash. For example, the following crontab command:

0 0 * * 1-3 /usr/bin/feeder.php

causes the script to be executed at midnight, Monday through Wednesday.

In order to change the contents of your crontab file, you need to use the crontab utility, which also automatically edits the correct file and notifies the dæmon that your schedule has changed. There aren't any special requirements to run a PHP script as a cron job, as long as it does not expect any input from a user.

Manipulating HTML Code

Even though your PHP-CLI scripts are not outputting HTML through a Web server, you still can use them to manipulate and produce HTML code. Because the script is written rather modularly, converting its output to HTML format involves changing only the format_feed function and modifying the call to mail(). This is done so the e-mail message can be recognized as a valid HTML document by the user's e-mail application.

One of the greatest advantages of scripting Web pages with PHP is the ability to mix dynamic statements directly with the static HTML code. As you can see from Listing 3, which shows an updated version of format_feed, this concept still works perfectly even when the script is not outputting to a Web page.

Listing 3. A Version of the format_feed Function that Produces HTML

// Feed formatting function

function format_feed ($feed, $url)
{

  ob_start();

  if (!is_object ($feed))
  {
  ?>
    <p>
    <b>Unable to load feed at
    <a href="<?= $url ?>"?>
    <?= htmlentities($url) ?></a></b></p>
  <?php
  }
  else
  {
    ?>

    <h1><a href="<?= $feed->url ?>">
    <?= $feed->title ?></a></h1>
    <p />

    <?php

    foreach ($feed->items as $item)
    {
    ?>
        <h2><a href="<?= $item->url ?>">
        <?= htmlentities ($item->title) ?></a></h2>
        <div width=500>
        <?= htmlentities ($item->description) ?>
        <hr>
        </div>
    <?php
    }
  }

  $res = ob_get_contents();
  ob_clean();

  return $res;
}


The trick that makes it possible to capture PHP's output in a variable essentially consists of engaging the interpreter's output buffer (disabled by default) by calling ob_start(). Once the appropriate information has been output, the script retrieves the contents of the buffer, then erases it and turns output buffering off with a call to ob_end().

Where to Go from Here

Although the news aggregator script I present in this article performs a rather complex set of functions—from grabbing content off the Web to parsing XML and formatting it in HTML—it requires only about 200 lines of code, including all the comments and blank lines. It is possible to write the same script in Perl or even as a shell script, with the help of some external applications such as wget, expat and sendmail. The latter approach, in my opinion, results in a complicated code base with plenty of opportunities for mistakes.

PHP-CLI rarely is installed by default on a machine running Linux, although you can count on Perl being readily available. Thus, if you have control over the make-up of the server on which you're running scripts and you're comfortable with PHP, there's no reason why you need to learn another language to write most of your shell applications. If, on the other hand, you're writing code to run on a separate machine over which you have no control, you may find PHP a slightly more problematic choice.

Marco Tabini is an author and software consultant based in Toronto, Canada. His company, Marco Tabini & Associates, Inc., specializes in the introduction of open-source software in enterprise environments. You can reach Marco through his weblog at blogs.phparch.com.

[Nov 27, 2002] Some Thoughts on PHP

Author:   John Lim    
Posted: 11/27/2002; 9:37:30 AM
Topic: Some Thoughts on PHP
Msg #: 2082 (top msg in thread)
Prev/Next: 2078/2085
Reads: 8413

Some Thoughts on PHP I just received this interesting email from Derek Comartin. I thought I would share his message and my response with you.

John,

I have been reading PHPEverywhere ever since I found it about a year back. I love reading it and your thoughts about the latest tech. Just recently I started using ADOdb for a project and love it. I am not a huge fan of PEAR's DB or PEAR in general (although I am using its SOAP package).

Anyways, the real point of my e-mail is that I am really getting frustrated with PHP. I have been developing applications with PHP for 3 years now, mainly developing intranet and CMS the like. My problem is that it seems like PHP is close to what I want it todo, but not quite. I would like to hear your thoughts and the thoughts of other php developers (people that use it everyday).

Let me say first of all I have absolutely no influence on the direction of PHP. I do not have CVS access to the PHP source code, and wouldn't have the time to contribute even if I wanted to. However some people might be interested in my opinion.

To me PHP is a pragmatic language. It is not based on any formal theory nor specification. It grew the same way as Perl, due to demand from skilled hackers. However Rasmus Lerdorf and company seem to be more keen on pruning the core language than the Perl gods and keeping it really simple. For example, to me the lack of the more advanced OOP features is a blessing. I was never impressed with C++ and its complexity, although I coded in it nearly every working day for 5 years.

(BTW, sorry if this is going to get long.. my real goal here is maybe you can post this on your site and hope to get some feedback in your comments section).

1) Templates Almost everyone agrees that mixing HTML and PHP is a bad idea. Personally I have developed my own template library that is simple and thin. Since PHP is geared toward web applications why in gods name don't they develop a SIMPLE template library built-into PHP. I cannot understand for 1 minute the point of smarty? I do think smarty is a very well designed library but I don't understand the point of making a library that introduces more business logic. Isn't the point of a template to seperate buisiness logic from UI? Who is coming up with this stuff?

The development of templates was an attempt to fight against complexity. This is good. Yes PHP is a template-based language, but that doesn't mean that good techniques preclude more advanced strategies for separating code,data and presentation. For very big scripts, we split code into functions and into several include files. We store data in an RDBMS for better management. So for very big web pages, it makes sense to split it into multiple files, and split presentation to template files too. Then we have a N-layer architecture of:

DATABASE 
   |
PHP BUSINESS LOGIC
   |
PRESENTATION LAYER TEMPLATES
   | 
PHP ENGINE 
   |
APACHE

From a theoretical point of view, perhaps Smarty has gone too far. Smarty does not merely deal with presentation issues, but has a full-blown programming language built-in. There is always the temptation to add functionality to something that began as a simple project. In some ways, Smarty compiled code is obfusticated PHP :-)

However from a commercial perspective, Smarty is cool. I can release a Zend encoded PHP product, and provide customization features by basing my user interface on Smarty, which the client can modify and even script without touching my compiled code.

So it really depends on your perspective. One man's Toyota is another man's Rolls Royce. And some people refuse to learn to drive and will never see the point of using Smarty.

(BTW: I have been wondering if someone has written a template library that is something like this:

If you had a template that had a <form id="myForm"> tag, then in your PHP you could modify tag properties etc... im not sure if ASP.net does something like this.. so your code would be:

$tmpl->myForm->setAction('myform.cgi');
$tmpl->myForm->setMethod('POST');

Kinda like how Javascript can minipulate objects, you could do with any HTML tag.. ie: forms, tables, yadda yadda

There are several libraries that do this already if you search on hotscripts.com. including (wink-wink) my company's product, phpLens which goes one step further in providing graphical ui designers/wizards. And my point of view is a little bit more radical - doing this without graphical aids is a step backward. For example this doesn't excite me:

$tmpl->myForm->DrawInput('text',$size=32,$maxlength=64);

because you lose the benefits of a graphical tool like dreamweaver that recognizes input tags for the obscure benefit of coding everything as objects. Half the power of MS.NET is the graphical tools of Visual Studio.NET.

Note that I had to use $size and $maxlength before you could even guess what the parameters of the function were. The beauty of HTML is that it is self-documenting.

2) Database

Thanks to you I use a great database abstraction. But why on earth isnt there abstraction built-in? I still like having functions for a specific API, but there should be db abstraction on top of that built in for speed.

Anyways these are just my random thoughts... I love PHP but there are too many things that are beginning to piss me off (did I also mention nonsense like how functions like explode, strstr have there haystack/needle arguments in different orders? Shouldnt this be common across all functions.... ah the little things.)

What are your thoughts?

PHP was developed to meet a need. PHP has grown organically, not because it was sponsored by big companies like Sun or IBM (eg java). People originally used PHP to create web-sites where the database was probably known; in contrast, database abstraction is only required if you are creating web applications that can be installed in different environments. I rarely do web-sites, most of my PHP work is for web-applications that run on Intranets/Extranets. That's how ADOdb came about. That's how PHP came about - to meet an immediate need.

So as PHP has matured, so has the needs become more sophisticated. Some people will always want PHP to do more and grow in more powerful ways (data abstraction, 100% OOP, etc), but as PHP growth is organic, you have to wait till someone faces the problem and comes up with the solution and post it to the net. This laissez-faire approach works because the number of PHP developers has reached a critical mass (perhaps when PHP4 was released).

Of course some things could have been better planned from the beginning of PHP, but no one would have started work till the last bit of the plan was nailed solid, which would have taken too long. Instead Zeev and Andi (and Rasmus?) are still very conservative about the core language, and they let you and me build whatever we like without comment. PHP-Nuke and Post-Nuke might never have been developed if Rasmus had blessed Midgard as the way to go. Of course there are people who say that the Nuke forks cannot compare to Zope or Soup or Whatever, or that the PHP api is not as nice as Java's or Python's -- but that misses the point. Millions of people are using and benefiting from the free software when programming in Java or Python or C# would have been too difficult. And this gives impetus for people to create better software.

-- John Lim PHPBuilder.com - Introduction to PHP5

PHP5 is not yet official but the development versions are already usable (and unstable!) so we can start to learn and practice the new features of the upcoming version of PHP. In this article I will focus in three major new features of PHP5:.

* The new object model
* Exceptions
* Namespaces

First of all a couple of disclaimers:

* Some of the techniques described in this article can be done with PHP4, but are presented anyway to make the whole article more readable.
* Some of the features described in this article may change in the final release of PHP5.

PHP5 has not been released yet and I don't know when that will be but you can already try and investigate the new features of the language by downloading and installing a PHP5 development version from http://snaps.php.net. There you will find Linux and Windows versions of PHP5 ready to be used. Installation proceeds as in any normal PHP distribution so go there and grab a brand new toy.

 

Message # 1016053:
Date: 04/12/03 07:01
By: Marcel Swinkels
Subject: Oh my god!

If this is the future for PHP why not start using JSP? :-(

 

Message # 1016064:
Date: 04/13/03 11:28
By: John C. Ghormley Profile
Subject: Look like Java to me

As an old time procedural coder, I didn't continue to pursue Java simply because I can't seem to get my mind around the OO paradigm when trying to think through a problem. So PHP was a great solution. Very procedural even if not politically correct for the times. Now, it seems the powers of PHP want to make it OO. That causes me a bit of concern and the concerns are these:
1) We're adding a lot of code overhead into the PHP code base to support OO.
2) Will that additional overhead slow the response time of PHP significantly?
3) If it does, how soon will the procedural elements begin to be extracted in favor of a more politically acceptable OO?
4) Assuming there is not degradation in performance, how soon will the pressure to conform to more politically acceptable practices cause the procedural elements to disappear?

On first read, I think i'd concur with Swinkels -- why not switch to JSP?


 

Message # 1016192:
Date: 04/20/03 17:24
By: Scott R.S.
Subject: RE: Look like Java to me

PHP CURRENTLY (4.3.x) outruns any JAVA code and 99% of the latest .NET stuff from MicroSoft/MajorGreedy!!! Mind you I spent YEARS as a die hard MS guru building major systems for investment and retail banks as well as insurance, medical and communications sectors using MS tools. I looked at moving to Java and being something of a purist found all the OOP crap (forgive me folks) to be much ado about nothing that simply adds significant amounts of time and thus expense to projects without being able to support the speed and stability enterprise customers demand. Further while Java is somewhat portable, it still has light years to go before it can compete with .NET in terms of speed... I kept looking, and then, the BEST OF BREED, PHP!!!! Portable, powerful, FAST when it's free and when you compile it, get out of the way!!!!!!!! What a piece of software!!!! Take a look at http://www.partysite.com for some compiled PHP in action, be sure to notice the transaction timer in the lower left corner of results, then keep in mind the database has 1.7 million rows in it right now. Let's see MS or Java do that in under a second, oh that's right, THEY CAN'T!!!! The math ALONE is too much for either to support at any speed, then factor in the amount of data involved and neither can hope to touch it... I know, I was CTO of a startup that TRIED to build something for insurance companies in WINDOWS and WITHOUT any math, and only a couple hundred thousand records CHOKED and locked up the server... Want REAL power, and speed (which is simply defined as "power in excess of a given task") then build in PHP and compile it!!!! Compiling PHP is now SO MUCH more affordable with the Small business program from http://ZEND.COM that it pays to compile!!!!

Scott....
Message # 1016118:
Date: 04/15/03 08:39
By: Zeev Suraski
Subject: PHP's direction - reassurance

Just to reassure the people here that don't want to see PHP becoming an OO language - have no worries, this is not going to happen.

We've definitely added lots of OO features to the Zend Engine 2, but all of the structured code features remain intact. PHP's built-in functions are and will remain procedural. I think Jean-Marc hit it well - we want to give authors of larger-scale projects, or those that buy into the OO model, the tools to write their apps better. They've been using OO in PHP 4, but were bumping into all sorts of problems and limitations. We have no plan or will to try and encourage people to move away from procedural programming if they're happy with it.
Message # 1016603:
Date: 05/29/03 01:36
By: Excorcist
Subject: This is so stupid

I can't believe this

In PHP4 as you may already know variables are passed to functions/methods by value (a copy is passed) unless you use the '&' symbol in the function declaration indicating that the variable will be passed as a reference. In PHP5 objects will be passed always as references. Object assignation is also done by reference.

WTF is that crap??? You're trying to rip php out of it's roots and make it some kind of psuedo java. WHat the hell? If this isn't a step backwards I don't know what is. My god I can't believe this.
Message # 1016746:
Date: 06/16/03 04:34
By: Zeev Suraski
Subject: RE: This is so stupid

You should be thankful, then, that you'd be able to enable compatibility mode and have your objects behave in the same way as previous versions of PHP have, and be passed by value.

If you consider the old behavior an advantage, in any way, then I believe you've never written an OO piece of code. That's fine, by the way - as PHP 5 will definitely not force you to write OO, it'll just make it a heck of a lot easier.
Message # 1016750:
Date: 06/16/03 10:16
By: David Fells
Subject: I guess IL is next...

Seems like the php team is on the right track with finally giving try/catch exception handling and providing access modifier keywords for class members. I'm just not really convinced of the necessity in using OOP in php...

In some tests I ran recently before deciding whether to completely rebuild or just reuse some old code someone else wrote for a new project, the OOP code they wrote ran approximately 10 times more slowly than the procedural code I wrote... by simply putting what would be a "class" in it's own include file and including as needed, you still have the basic reusability of OOP without the extra compile/execute time of objects.

I'm just afraid the addition of namespaces, exception catching, catchalls, and access modifiers are only going to make the performance of OOP in PHP get worse =( I just hope they don't choose to go to an IL/JIT model to compensate ! Yuck.
Message # 1016549:
Date: 05/21/03 19:27
By: Brandon Goodin
Subject: RE: Look like Java to me

Let me preface by saying.. 'to each their own'.

Having been a long time Java programmer and currently still, I find that many of the comments that have been made in this thread regarding java are outdated and even innacurate.

I don't have the time to go back and speak on each point specifically. But, from a personal standpoint Java has been progessing as fast and furious as other technologies (including php). Short comings from 2 years ago don't apply to today.

To state some positives about Java:
- Object generation and garbage collection has improved drastically.
- Various open-source and commercial frameworks have emerged to allow for quick and efficient assembly of applications (client and server). Most use good OO design patterns.
- Because of the decoupling of various layers of the application better code management is possible. (i.e View/Controller/Logic/Data Layer/Web Services)

I encourage you all to post your statements to a Java discussion board and see what responses you get. You might learn something about Java that you didn't know.

Personally, I like php. It's a great language... for the web and for small-midsize to small jobs. I got away from the page scripting as a mainstay because it became to difficult to manage in a team environment. All of the dependencies on the view passing the right parameters to the next page and the tight coupling with the data layer in the end makes things too complex. I use good php coding standards. But, it still doesn't compete with a well formed Java envrionment. Once the job gets to a certain size I find that I can create in Java a lot faster.

I think the direction that php is going with it's Java/C# OOP look and feel is a good thing. But, even with php5 it appears it has a ways to go before it's competing with the maturity of Java/C#/Python type OOP languages. BTW for all the complaining against OOP I find it humorous that php is adopting the very principals you dislike. Procedural will always be around. But in the economy of scale (IMHO) OOP wins.

So, long live PHP OOP!!! :-))

Yahoo Goes PHP in Open Source Embrace By Ryan Naraine

Mega portal Yahoo (Quote, Company Info) has switched to the PHP scripting language for its back-end programming, a decision that's sure to bring smiles to the faces of open-source advocates.

The Sunnyvale, Calif.-based Yahoo is undergoing a switch from a proprietary system written in C/C++ to PHP (define) for its backend scripting, according to a company engineer in a case study presented this week at the PHPCon 2002 conference.

Michael Radwin, who is co-leading the PHP crusade at Yahoo, told the conference that Yahoo's size and complicate server-side software made the switch to PHP a no-brainer, pointing to the huge savings cost associated with migrating to an open-source platform.

He said Yahoo, which serves more than 1.5 billion page views a day, had already adopted open-source software like Perl (define), Apache (define) and FreeBSD (define) to run its 74 Web properties, which includes 25 international sites.

Back in 1994, when Yahoo was launched, Radwin said free technologies like PHP did not scale and were considered too "immature" to run large, complex destinations. However, the growth of the open-source movement has spurred a change in thinking because languages like PHP aid performance and integration, he explained.

The Apache-backed PHP project, which was created in 1995 by Rasmus Lerdorf, has seen startling usage growth since 1999 and its adoption by a high-profile Web property like Yahoo has sent tongues wagging in the developer community.

Because PHP is embedded within tags, code writers can jump between HTML (define) and PHP (similar to ASP and Cold Fusion) instead of having to rely on heavy amounts of code to output HTML. PHP is shipped standard with a number of Web servers, including RedHat Linux.

Radwin, who has worked as a Yahoo engineer since 1998, said proprietary scripting language became a "pain in the neck to maintain and use" and was difficult to integrate with third-party software. He said coding in C++ (define) was too cumbersome and prone to buffer overflows, making it a security risk for Yahoo.

Yahoo, which has felt the financial crunch from the online advertising recession and has been dabbling with paid services to stem the flow of red ink, said cost savings drove the PHP migration plan.

"Yahoo is a cheap company. (We) can't afford to waste engineering resources (on proprietary coding)," Radwin said, adding that the company first moved to embrace open-source technology back in 1996 when it replaced the Filo server with Apache. Since then, the company has moved some of its database management from Oracle to the open-source MySQL.

"Server-side languages is the natural next step," Radwin told the conference, touting improved features, performance and integration within PHP. Yahoo chose PHP ahead of alternatives like Perl, ASP or Cold Fusion mostly because it was designed for server side Web scripting and because of the large, open-source developer community that has helped improve the integration and training of software engineers.

He said "simple and clear syntax" in the PHP language fit perfectly with Yahoo's plans, adding that tests done by the portal were very successful.

Yahoo has already started using PHP for new properties, like the remember.yahoo.com site which was created as a September 11 tribute. Other early adopters of PHP at Yahoo included the PayDirect Site, the Classifieds - "Express" premium service, the personalized Yahoo News feature and almost the entire Yahoo Travel site.

The ionCube PHP Accelerator Home

The ionCube PHP Accelerator is an easily installed PHP Zend engine extension that provides a PHP cache, and is capable of delivering a substantial acceleration of PHP scripts without requiring any script changes, loss of dynamic content, or other application compromises. 

Unlike scripting languages such as Microsoft ASP1, compilation of any unchanged scripts is entirely eliminated when PHPA is installed, and so a typical PHP request incurs no compilation overhead at all.

PHPA is free, and not only the top performing non-commercial solution of its kind, but also a match for the commercial alternatives. Delivering typically up to a 5 times speed gain and with a near 10 times speed-up measured with some Smarty based applications, sites such as Yahoo! have found PHPA to be the ideal PHP script caching solution. The testimonials give some user reactions to PHPA.

Create dynamic sites with PHP & MySQL

This tutorial shows you how to use two open source, cross-platform tools for creating a dynamic Web site: PHP and MySQL. When we are finished, you will know how dynamic sites work and how they serve the content, and you will be ready to serve your own dyn...
Publisher: www.codewalkers.com
 

O'Reilly Network GoLive 6 Adobe's Open Source Embrace [May. 31, 2002] by Glenn Fleishman

Author's Note -- Before GoLive 6 shipped, I would have tried to dissuade anyone but an already experienced Unix administrator or someone who needed to become one as part of a job from trying to self-install all the components needed to run MySQL, PHP, Apache, and JSP on a Mac OS X machine or under Windows XP or 2000. If you're already serving pages that need these elements and want to migrate them to a desktop server, or want to start serving content that requires these elements, the GoLive Preconfigured Servers substantially lower the bar.

In this article I'll show you where these components are located in the GoLive 6 shrink-wrap, and then once you have a handle on these tools, I'll show you how to upgrade them the good, old-fashioned, open source way.

 

GoLive 6 Breaks From Tradition

Adobe has never expressed close feelings for either open-source software or the Unix and Linux platforms. As Linux has risen in popularity and open source has increased in quality and availability, Adobe provided only sporadic and incomplete support. Photoshop under Red Hat? Nope. But Acrobat Reader for certain Unix flavors? Sure.

GoLive 6 marks a decided change in attitude from Adobe. In the interests of a competitive product and a complete server feature set, the company leapt into bed with Apache, Tomcat (a JSP server), MySQL, and PHP under both the Darwin environment of Mac OS X and the modern NT-style architecture of Windows XP and 2000.

As Derrick Story noted in the first article of this series, GoLive emerged from the graphic design world in which the program started as a WYSIWYG page layout tool. Over time, it evolved into a full-featured editor with support for JavaScript, Cascading Style Sheets, and Dynamic HTML, working alongside a drag-and-drop site management system.

At the same time as GoLive, Inc. (and later Adobe-developed GoLive), Macromedia pushed and pulled its own page and site tool, Dreamweaver. As GoLive became more graphically intense and expanded its reach into directly editing different kinds of media (QuickTime, images, vector art) and integrating with other Adobe graphic tools (Photoshop, Illustrator, ImageReady, LiveMotion), Dreamweaver kept climbing up the code ladder, including more and more built-in or add-on support for code development that worked alongside page and site creation.

Dreamweaver UltraDev, for instance, was a powerful package that supports authoring ASP, JSP, and ColdFusion. It integrates many kinds of databases and database conduits with page layout tools, and provides end-to-end support in the case of JSP (with their JRun server) and ColdFusion (part of their Allaire merger) for design to code to database to server testing and development. (Dreamweaver MX expands this to incorporate UltraDev, and to work with and create Web services and Web applications using JavaServer Pages, ColdFusion, SOAP, and .Net.)

GoLive lagged on the code side, and its initial foray into database integration, called Dynamic Link, only worked with ASP servers running ADO DB conduits or Microsoft Access databases. It was frustrating to configure and use, and I only know a handful of users who had the right combination of server and savvy to build a functioning system.

Adobe wisely jettisoned Dynamic Link, replacing it with Dynamic Content. The change wasn't cosmetic, but reflects instead a significant improvement in features, flexibility, and troubleshooting. GoLive 6 supports ASP, JSP, and the Internet favorite PHP for database integration of content. It also ships with a full set of preconfigured servers for both Mac OS X and the Windows XP/2000 environments. The preconfigured servers include Apache 1.3.22 with PHP 4.1.2 precompiled in; Tomcat 3.2.2, a JSP server; and MySQL 3.23.47.

For many users, the preconfigured servers allow them to suddenly tap the potential of database integration with a Web site without the vast ramp up in knowledge typically required to compile and configure server software. This package is simple to get started with, but, as with any commercial release, hard-won tips help smooth the process.

Installing GoLive 6 Preconfigured Servers

The preconfigured servers ship on a disk bound into the Adobe Web Workgroup Server manual. (More on AWWS later: it's a JSP-based WebDAV server that supports versioning via a GoLive interface.) Once installed, a set of test scripts allows some configuration and displays example results and projects.

Installing it is typically a snap. The installation system is slightly different under Windows 2000/XP and Mac OS X, but both involve a package-style graphical installer, which includes screens of instructions. The Apache/PHP and JSP servers are in the Dynamic Content folder. This single installer puts all of the software in the right place.


Related Reading

Web Database Applications with PHP & MySQL
By Hugh E. Williams, David Lane

Table of Contents
Index
Sample Chapter
Read Online--Safari


The installer allows you to set non-default ports for any of the associated applications. PHP is compiled as part of Apache, so Apache calls it internally. Tomcat is a JSP server that Apache connects to. MySQL is a server that any scripting language can interact with through the appropriate conduit or interface.

MySQL's installer is found in the Extras folder, which also has the JDBC driver (the Java Database Connectivity or database conduit) for MySQL.

To install MySQL, you need to follow the instructions in the Readme file, which include copying the install script to the local hard drive, launching Terminal, and creating a new user account. The instructions are actually quite clear and more than adequate.

MySQL, as installed, still requires a command-line entry to set the root password for the server. The install script offers up a reminder to run these two commands:

./bin/mysqladmin -u root -p password 'new-password'
./bin/mysqladmin -u root -h localhost -p password 'new-password'

The "localhost" item is literally "localhost": if your system identifies itself by a host name, "localhost" isn't the right value. MySQL is very particular.

When you're choosing MySQL passwords, keep in mind a later issue we'll cover: MySQL passwords are stored in the clear in well-known locations as part of the GoLive Dynamic Content system. The passwords are enveloped in a script file that prohibits access. But nonetheless, they're in the clear on your server. In my case, I opted to create a special, limited permission account that wouldn't wreak havoc if my server were compromised. Adobe should take note: this is a giant, gaping security error.

The iconv library is also in the Extras folder; it must be installed into your PHP directory following the instructions in the same folder for PHP to work. This appears to be a licensing issue.

The installation process also creates server start, stop, and restart scripts for all servers and individual servers in the package.

Both the Apache/PHP and JSP servers can be used as actual production systems by editing the configuration file. The installer creates shortcuts for opening and editing the configuration files associated with the two servers, or you can just use Terminal to edit the files with vi or another text editor.

Many GoLive users, even sophisticated ones, may balk at the command-line SQL sequences that MySQL (and other databases) require. A colleague pointed me to the superb phpMyAdmin set of scripts that put a Web front-end onto MySQL administration. Download the source code from phpmyadmin.sourceforge.com.

 

Why and How I Installed PHP4, MySQL, and Apache on Windows 98
Sep 27, 2000, 18 :29 UTC (1 Talkback[s]) (1052 reads) (Other stories by Edward Tanguay)

Originally appearing in The Web Developer's Journal.

By Edward Tanguay

Four months ago I was selected as Web developer for a large Web site project for six hospitals here in Berlin. It was going to be an exciting project in which I would work together with a marketing company to realize a network of Web sites. However, when we had the first meeting, the head of the computer department said, "Wait a minute. You program in ASP? We run Linux boxes here and can't justify the cost or security risk of an NT-Server." They were unwilling to budge and I didn't want to force Microsoft on them and then have to work with disgruntled system administrators, so I backed out gently and declined the contract.

Beyond ASP: JSP, ColdFusion or PHP

Since that day I've been looking for ways to extend my server-side programming skills beyond the powerful but environment-limited Active Server Pages. I concluded that I basically had three choices outside ASP for server-side scripting: JSP, ColdFusion and PHP. The first, JSP, is promising but still has a relatively small community and a lack of ISPs which support it. In addition, if you use the JSP server from Allaire it is quite expensive. The second choice, ColdFusion, also from Allaire, provides you with a powerful and robust server-side scripting environment centered around databases and e-commerce, but again, the problem is it simply costs too much. If you don't have access to the multi-thousand dollar Enterprise server, you're out of luck (the free ColdFusion Express server doesn't even support session variables - not very useful).

LAMP is red hot and free

PHP, on the other hand, is free. It is combined with three other technologies to form a powerful Web development solution abbreviated LAMP: Linux (operating system), Apache (Web server), MySQL (database) and PHP (scripting language). Even with MySQL's insistance that businesses pay a nominal fee for its use, Linux, Apache and PHP are absolutely free which make the LAMP solution the most cost-effecive solution for individuals, universities and businesses. Web devlopers wishing to acquire valuable scripting skills can do so for free. On top of that, LAMP is generally known to be more secure and robust than other solutions (less crashing, less rebooting, inherent UNIX security). On top of that, LAMP has one of the largest, most active, most dedicated communities on the Web. PHP and the LAMP solution was clearly the best choice for me and I was excited.

The Linux hurdle

However, if you are a Windows user, learning Linux is like being parachuted into Italy without knowing Italian. You will be hopelessly and thoroughly lost at the UNIX prompt. Although my repeated forays into the Linux world have enabled me to install Suse Linux 6.4, set up the X Window System and even use the vi editor, I still lack so much basic knowledge of Linux that even the simplest things such as unpacking files or installing software bring me to a paralyzing stop. So even if you are the type of Windows user who can buy a $50 computer book on almost any application and become an expert in it by the end of the week, Linux is not something you are going to learn in a week, or a month or even a year without an inordinate investment of time, effort, paradigm shifting and lots of long, frustrating nights. Hence LAMP is not an option for the casual Windows user wanting to learn PHP scripting.

Settling for WAMP

Luckily, PHP, MySQL and Apache can also run on Windows (hence WAMP). Note that this is not the most stabile platform to serve your pages to the world, but it is an adequate solution if you want to learn and begin developing with PHP/MySQL while remaining in your familiar Windows environment. You can install Apache, PHP and MySQL on your Windows 98 machine, then upload your applications via FTP to a more stabile LINUX or UNIX server. WAMP is a good compromise for Windows-based Web developers who want to expand their server-side scripting skills into PHP and MySQL.

WAMP installation cryptic but not impossible

It took me a full seven days until I had Apache, PHP and MySQL on my Windows 98 installed, configured and working. It was not easy. The Web is full of well-meaning but conflicting manuals which give you instructions such as to enter "/php4win/" when it should be "c:/php4win/" - that one took me two days to figure out. Another two days was spent downloading incorrect MySQL packets (the manuals tell you to "download MySQL" but when you get to the page you are faced with a choice of about 30 different download possibilities). Luckily there were some very helpful people on the Web Developer's List who kept helping me until I got it. Thanks again to all of you!

Free workshop on installing PHP4, MySQL, Apache on Windows 95/98

If you want to install PHP4, MySQL and Apache on Windows 95 or 98, take my free online workshop on how to do it. This 14-step workshop has explicit instructions and screen shots which will lead you past all the pitfalls. With this Workshop, you can have PHP4, MySQL and Apache installed, configured and working on your Windows 98 within the hour.

Edward Tanguay is a Web developer and language trainer based in Berlin. For more diaries and tips on development visit Edward's Web Developer Site.

[Jan 23, 2000] Linux.com - Featured Articles PHP Questions - January 23rd, 2000
   by Jeff Alami
-- another intro

[Jan 23, 2000] http://www.phpbuilder.com -- great site. If you never visited it stop here. You should visit it first.

[Jan 23, 2000] http://phpclasses.upperdesign.com

[Dec 25, 1999] dotcomma; Article; An Introduction to PHP -- short intro.

LinuxPlanet: Adding PHP to Apache on Linux (Dec 23, 1999)
osOpinion: PHP: a silent killer (Dec 22, 1999)
LinuxPower: Interview with the PHP Team (Nov 15, 1999)
Network Computing: Web-Page Generator PHP Gets A Much-Needed Jolt in Version 4 (Nov 02, 1999)
Apache+mod_ssl+PHP Step-by-Step (Sep 11, 1999)

[June 24, 1999] Web mail in PHP [Part 1] 

[June 20, 1999] .MySQl-PHP club [.ru]  -- in Russian

[June 14, 1999]Linux Today Ext2 Perl versus PHP for Web Design -- interesting discussion (links to the original papers are reproduced below):

InfoWorld: Treasure trove: PHP offers features that will make your Web apps sparkle (Jun 19, 1999)