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.
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);
?>
Trending Topics
| You Need A Budget | Feb 10, 2012 |
| The Linux powered LAN Gaming House | Feb 08, 2012 |
| Creating a vDSO: the Colonel's Other Chicken | Feb 06, 2012 |
| Your CMS Is Not Your Web Site | Feb 01, 2012 |
| Casper, the Friendly (and Persistent) Ghost | Jan 31, 2012 |
| Razor-qt 0.4 - Qt based Desktop Environment | Jan 30, 2012 |
- Fun with ethtool
- Parallel Programming with NVIDIA CUDA
- 100% disappointed with the decision to go all digital.
- Readers' Choice Awards 2011
- Linux-Based X Terminals with XDMCP
- Validate an E-Mail Address with PHP, the Right Way
- You Need A Budget
- Build Your Own Arcade Game Player and Relive the '80s!
- The Linux powered LAN Gaming House
- Why Python?
- I use Wireshark on a daily
3 hours 26 min ago - buena información
8 hours 33 min ago - One important "bucket" that I didn't note (désolé si qqun deja d
9 hours 33 min ago - Gnome3 is such a POS. No one
19 hours 1 min ago - Gnome 3 is the biggest POS
19 hours 11 min ago - I didn't knew this thing by
1 day 1 hour ago - Author's reply
1 day 4 hours ago - Link to modlys
1 day 5 hours ago - I use YNAB because of the
1 day 5 hours ago - Search
1 day 11 hours ago





Comments
I have same problem of
I have same problem of undefined function mysql_connect(); when i use php from the command line interface. i know mysql libraries are not loaded into the php which are dynamic so you said dl("mysql.so") make it working, so i am new to cli so where i have to write this line which laod the mysql modules,Thank you.
I found solution,i like you
I found solution,i like you aricle wriiten above.Thank you
Regards
Biney
PHP
PHP is very easy to use. If you have some experience of C you won't have any problems to get started with PHP. Even HTML coders can start integrating PHP into their pages straight away. But maybe PHP is too simple. What do I mean by that? The simplicity of PHP means that almost anyone can write some scripts and as a result there is a lot of badly designed code out there. This gives PHP a bad name it does not deserve because it is a very powerful tool. PHP is designed for building Web applications that are scalable up to a very large number of users. With PHP 5 many developers finally got the robust support for object oriented programming they where waiting for but also its XML and MySQL support was much improved. There is much discussion about if PHP is "enterprise ready" - I truly believe it is since it reached version five.
Not able toconnect to mysql in crontab through PHP
hi there
I am not able to connect to mysql in a PHP script that is running through crontab when it is time for crontab to run PHP script i get an error mesage in a mail that Fatal Error-Call to undefined function mysql_connect() in the script .otherwise the script is running OK in explorer or through linux command line ie. php filename.php.
I am using like - mysql_connect("localhost",$uname,$pass);
to make the connection.
plz help
Undefined mysql_connect...
For the last half hour I was trying to deal with the same problem,
And I just remembered that the "dl" function might do the job.. and looky here.. it did!!!! :)
NOW TO THE SUBJECT:
When executed from Cron, or command line, a PHP script might not recognize the MySql functions, this is because the required libraries are not loaded. It can be simply fixed by the "dl" function in the following manner:
dl("mysql.so"); //loads the mysql library/module or perhaps you might be using a different library than mysql.so
After this line.. one can use the mysql functions as one pleases.. hopefully :)
THANK YOU
dl("mysql.so"); was exactly what i was looking for, thanks so much!
Thank you so much.
This solution was a great help to me. Thanks so much. You rock!
Undefined mysql_connect...
For the last half hour I was trying to deal with the same problem,
And I just remembered that the "dl" function might do the job.. and looky here.. it did!!!! :)
NOW TO THE SUBJECT:
When executed from Cron, or command line, a PHP script might not recognize the MySql functions, this is because the required libraries are not loaded. It can be simply fixed by the "dl" function in the following manner:
dl("mysql.so"); //loads the mysql library/module or perhaps you might be using a different library than mysql.so
After this line.. one can use the mysql functions as one pleases.. hopefully :)
Re: PHP as a General-Purpose Language
this is really a very good solution to general shell scripting. I was doing this to export data to xml files, do straighforward oracle database extraction and mysql backups.
the problem i ran into is that, like mentioned in the article, php is not readily available on all boxes and cannot always be installed...this can really become a problem.
otherwise, an excellent solution, to which php is really well suited.
Re: PHP as a General-Purpose Language
PHP makes me sad. :(
Re: PHP as a General-Purpose Language
Listing 2 doesn't seem to be a configuration file.
SimpleXML
Have a look at SimpleXML. It is available since PHP5 and it makes life much easier for simple xml-files like RSS.
Re: SimpleXML
Check out this article that shows how to use SimpleXML to parse a RSS feed from php-planet.net