<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Mind Tree &#187; PHP</title>
	<atom:link href="http://hurricanesoftwares.edublogs.org/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://hurricanesoftwares.edublogs.org</link>
	<description>Technology made simple.</description>
	<lastBuildDate>Thu, 26 Jun 2008 09:19:38 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Friendly URLs in PHP: why do you care?</title>
		<link>http://hurricanesoftwares.edublogs.org/2008/06/24/friendly-urls-in-php-why-do-you-care/</link>
		<comments>http://hurricanesoftwares.edublogs.org/2008/06/24/friendly-urls-in-php-why-do-you-care/#comments</comments>
		<pubDate>Tue, 24 Jun 2008 11:47:18 +0000</pubDate>
		<dc:creator>Ashish</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.hurricanesoftwares.com/?p=171</guid>
		<description><![CDATA[Nice URLs, readable URLs, search-engine-friendly URLs. Different names same deal.
It can’t really be disagreed on that something like example.com/index.php?page=article&#38;id=409 is not nearly as nice as example.com/article/409.
Turns out this isn’t all that hard with PHP &#8211; infact it can turn into something that’s very useful from more than just a readability viewpoint.
The Plan
What we’re going to [...]]]></description>
			<content:encoded><![CDATA[<p>Nice URLs, readable URLs, search-engine-friendly URLs. Different names same deal.</p>
<p>It can’t really be disagreed on that something like example.com/index.php?page=article&amp;id=409 is not nearly as nice as example.com/article/409.</p>
<p>Turns out this isn’t all that hard with PHP &#8211; infact it can turn into something that’s very useful from more than just a readability viewpoint.</p>
<p><strong>The Plan</strong></p>
<p>What we’re going to do is capture everything past a particular point in our URL and pipe it to PHP, we’re going to let PHP do most of the the legwork.</p>
<p>* Using mod_rewrite we get everything past a particular point.<br />
* We will then pass that into a PHP get variable. We’ll use “p”, you can use anything.<br />
* In our PHP we will define “rules” for our URLs with very simple regular expressions.<br />
* When something matches, we’ll get the appropriate page &#8211; otherwise we’ll give back a 404.</p>
<p><strong>mod_rewrite</strong></p>
<p>Yep, this article is purely from an Apache perspective, so I assume that you not only have Apache on your webserver, that you also have enabled mod_rewrite.</p>
<p>If you haven’t enabled mod_rewirite, it’s usually something like this in your http.conf:</p>
<p>LoadModule rewrite_module modules/mod_rewrite.so</p>
<p>Remember to restart Apache afterwards.</p>
<p><strong>.htaccess</strong></p>
<p>Let’s get .htaccess out of the way now. These are special files that you may, or may not have come accross. Basically, Apache will read these set of definable rules and determines what to serve when you visit a page.</p>
<p>In this case we’re going to use mod_rewrite rules. So, first create a file called .htaccess and open it up. (To Windows folk &#8211; It really has no “filename”, this might confuse some of the poorer text editors.)</p>
<p>To start with, we’re going to check if mod_rewrite is enabled &#8211; if it isn’t then Apache will return an internal server error (500).</p>
<p>All our rules will go inside this block.</p>
<p>First we need to enable the rewrite engine and set our base.</p>
<pre>RewriteEngine on
RewriteBase /</pre>
<p>The RewriteBase will tell Apache exactly where our capturing needs to come from, what the relative path is.</p>
<p>In our case we’re assuming we’re rewriting the root of a URL. If your script resided in a sub-directory like http://example.com/test, RewriteBase would have to be written like so:</p>
<pre>RewriteBase /test</pre>
<p>Our first rule will tell Apache where to go when we haven’t specified anything, in this case we simply want to go to index.php:</p>
<pre>RewriteEngine on
RewriteBase /

# Nothing - Go to index.php
RewriteRule ^$          index.php  [L]</pre>
<p>RewriteRule is how we define our actual rules.</p>
<p>Rewrite rules use regular expressions (regex for short), a kind of special text processing language, to define the rules. They can become very useful if you learn them properly, and we shall be using them later when we write the PHP portion of this article. PHP comes with reasonably good regex support built in.</p>
<p>In this case our regular expression is ^$. The caret symbol, ^, means “At the start”. The dollar sign, $, means “At the end.” So this pattern effectively matches nothing, there is nothing between the two symbols.</p>
<p>Don’t worry if regular expressions are confusing at first, there are many tutorials on it around.</p>
<p>The second part of RewriteRule defines where our rule goes to, in this case we always want an empty path to go to index.php.</p>
<p>The last part in square brackets defines a special flag, here we use the L flag. L defines this rule as the “last one” &#8211; if this rule matches then Apache will disregard any further ones.</p>
<p>Our next rule is the one that we came here for:</p>
<pre>RewriteEngine on
RewriteBase /

# Nothing - Go to index.php
RewriteRule ^$          index.php       [L]

# If anything matches, send the path to index.php
RewriteRule (.*)        index.php?p=$1  [L]</pre>
<p>In regex a fullstop means “any single character” and asterisk means “one or more of the previous character”. So our pattern is effectively &#8211; any amount of any character or simply, everything.</p>
<p>The parentheses around the rule indicate we want to group that match, and use it later. We do use in defining where our pattern goes to. You refer to groups with the dollar sign and the number of group. (Groups start at 1.) Again we will define this as the last rule with [L].</p>
<p>So with these two rules http://example.com will invisibly redirect to index.php and http://example.com/page/409 will rewrite to index.php?p=page/409.</p>
<p>Unfortunatly, if you try to go directly to any other file or directory, it will not show up &#8211; Instead the path will get sent to index.php! We can use RewriteCond to add additional conditions to rectify this situation.</p>
<pre>RewriteEngine on
RewriteBase /

# Nothing - Go to index.php
RewriteRule ^$          index.php        [L]

# Condition - requested path is not a file or directory.
RewriteCond %{REQUEST_FILENAME}         !-f
RewriteCond %{REQUEST_FILENAME}         !-d

# If anything matches, send the path to index.php
RewriteRule (.*)        index.php?p=$1  [L]</pre>
<p>In a little bit of slightly backward behaviour, when Apache finds a rewrite rule it will go back to see if there were any conditions and check those before finally matching. So these conditions must appear before the rule.</p>
<p>The first parameter is what we test against, it refers to a special server variable, in this case REQUEST_FILENAME. The second parameter is our actual condition. -f asks “Is an existing file” and -d is directories.</p>
<p>Since we only want to continue if the match is not a file we can use a !, so our final patterns are !-f and !-d.</p>
<p>Our rewrite ruleset is nearly complete, but there’s one tiny thing, sometimes you may want to pass GET parameters around in the URL the same way you normally would, as it stands these will be ignored by Apache when rewriting. We can use a flag to append all extra request parameters to the URL &#8211; QSA.</p>
<p>Our final .htaccess file looks like this:</p>
<pre>RewriteEngine on
RewriteBase /

# Nothing - Go to index.php
RewriteRule ^$          index.php       [L]

# Condition - requested path is not a file or directory.
RewriteCond %{REQUEST_FILENAME}         !-f
RewriteCond %{REQUEST_FILENAME}         !-d

# If anything matches, send the path to index.php
RewriteRule (.*)        index.php?p=$1  [QSA,L]</pre>
<p>If anything about mod_rewrite is confusing it’s worth knowing that the documentation on it is actually not all that terrifying and can help you understand it much better.</p>
<p><strong>Using PHP to get the requested URL</strong></p>
<p>Our rewrite rule will pipe everything into index.php as a GET parameter called “p”. So everything in our script will need to be included through this.</p>
<p>To start our index.php file we need to define a list of matches.</p>
<pre>/*
 * Work out what page we are on
 */
$page_rules = array(
  "index" =&gt; "home.php",
  "about" =&gt; "about.php"
);

$page_val = (isset($_GET['p'])) ? $_GET['p'] : "index";
</pre>
<p>$page_rules is an associative array pointing matched rules to special pages. You can keep your eventually pages whereever you like, for our example we’ll simply have a “pages/” subdirectory where these will go in.</p>
<p>We set $page_val to our “p” parameter if it was set, otherwise defaulting to index.</p>
<p>Next we go through all our rules and find if we’ve matched one with our parameter.</p>
<pre>
/*
 * Work out what page we are on
 */
$page_rules = array(
  "index" =&gt; "home.php",
  "about" =&gt; "about.php"
);

$page_val = (isset($_GET['p'])) ? $_GET['p'] : "index";

/*
 * Iterate through rules and test them on our request
 */
$match = NULL;

foreach($pages as $regex =&gt; $page_to)
{

  if(preg_match("/^".$regex."$/i", $page_val))
  {
    $match = $page_to;
    break;
  }

}

/*
 * If we didn't match anything deliver a 404 or include our file
 */
if($match === NULL)
  die("404");
else
  require "pages/".$page_to;
</pre>
<p>We now use preg_match to match against each of our rules.</p>
<p>For our index rule, the regular expression looks like /^index$/i. The forward slashes indicate the start and end delimeters of the regex, we can use extra flags to define special things, in this case we use the i flag which indicates that the match is case insensitive.</p>
<p>When we match a rule, we save the page name, then serve it later, or give a 404 message if not. (Your 404 message should be a lot better &#8211; this is a simple example after all.)</p>
<p>At this point our rewriting will work perfectly fine. There’s a few issues to work out first.<br />
<strong>Small issues</strong></p>
<p>First off, if you go to http://example.com/about the rule works, but if you go to http://example.com/about/ then nothing matches &#8211; our p variable has changed with that one character!<br />
Luckily we can expand our regular expression to account for this. Question mark, ?, means “the previous character none or more times”. So /? would mean “forward slash or no forward slash”, except that as we know, forward slash means something in regular expressions. To escape characters in regex simply use the backslash character. The correct match is \/?.<br />
Our new rule check looks like this:</p>
<pre>if(preg_match("/^".$regex."\/?$/i", $page_val))
{
$match = $page_to;
break;
}</pre>
<p>You may be starting to think that regular expressions can start to look messy the more complicated they get &#8211; you’d be right, but that doesn’t discount how useful they can be. A regular expression can be broken down into smaller parts if necessary.<br />
This leads on to our second problem, if any of our matches have a forward slash in, which they most likely will, you will get an error when hitting the regex because it would be unescaped. A quick str_replace will sort that.</p>
<pre>$regex = str_replace("/", "\/", $regex);

if(preg_match("/^".$regex."\/?$/i", $page_val))
{
$match = $page_to;
break;
}</pre>
<p><strong>Grouping</strong><br />
This is all well and good, but if you have a URL like our initial example of http://example.com/article/409 surely you’d have to make a new rule for each ID? Luckily we can leverage the power of regex to do that for us.<br />
First we need to ammend our rules to match /article/ and any number. This is done like so:</p>
<pre>$page_rules = array(
  "index"          =&gt; "home.php",
  "about"          =&gt; "about.php"
  "article/[0-9]+" =&gt; "article.php"
);</pre>
<p>[0-9] is a range, a single number from 0 to 9. And whereas ? means “zero or more times”, in this case we need to use plus, + which means “one or more times“. So we’re now matching any integer.<br />
Great, our rule works! But it’s useless to us if we can’t get that parameter out. Well, first we need to define this as a group in our regex by using parentheses, the same way we did in our .htaccess rules before.</p>
<pre>$page_rules = array(
  "index"            =&gt; "home.php",
  "about"            =&gt; "about.php"
  "article/([0-9]+)" =&gt; "article.php"
);</pre>
<p>To get our groups out of our regular expression we need to use the third parameter of preg_match, in which we pass in an array that will then be filled with our groups.<br />
Our foreach loop needs to look something like this:</p>
<pre>$match = NULL;
$matches = array();

foreach($pages as $regex =&gt; $page_to)
{

$regex = str_replace("/", "\/", $regex);

if(preg_match("/^".$regex."\/?$/i", $page_val, $matches))
{
$match = $page_to;
break;
}

}</pre>
<p>Great, now if you tried to go to /article/409 and did a print_r of $matches, you’d get something like:<br />
Array</p>
<p>(</p>
<p>[0] =&gt; article/43/</p>
<p>[1] =&gt; 43</p>
<p>)<br />
The first entry is filled with the entire pattern, the second one is our requested ID &#8211; the group we defined in our match.<br />
Notice that because we’ve defined any number, if you try to enter anything other than a number into the URL as an ID you will get given a 404 &#8211; This can act as a kind of first-defense validation for input variables.<br />
This is almost the end of the article, however we can make this a little nicer to work with.<br />
<strong>Named groups</strong><br />
Being able to refer to something like $_GET[’id’] is a convenience, there’s a name. $matches[1] is not so easy to dechyper &#8211; or even keep track of, what if we add another group that appears before it like a category name &#8211; the group number may shift.<br />
Luckily with regex we can name our groups using the simple syntax of ? inside the start of the group. Our new rules can now look like this.</p>
<pre>$page_rules = array(
  "index"                 =&gt; "home.php",
  "about"                 =&gt; "about.php"
  "article/(?[0-9]+)" =&gt; "article.php"
);</pre>
<p>Now when you print_r $matches you get:<br />
Array</p>
<p>(</p>
<p>[0] =&gt; article/43/</p>
<p>[id] =&gt; 43</p>
<p>[1] =&gt; 43</p>
<p>)<br />
You can still refer to the group as $matches[1], but we’re also given the option of $matches[’id’].<br />
<strong>Conclusion</strong></p>
<p>Our final PHP script looks like this:</p>
<pre>/*
* Work out what page we are on
*/
$page_rules = array(
"index"                 =&gt; "home.php",
"about"                 =&gt; "about.php"
"article/(?[0-9]+)" =&gt; "article.php"
);

$page_val = (isset($_GET['p'])) ? $_GET['p'] : "index";

/*
* Iterate through rules and test them on our request
*/
$match = NULL;
$matches = array();

foreach($pages as $regex =&gt; $page_to)
{

$regex = str_replace("/", "\/", $regex);

if(preg_match("/^".$regex."\/?$/i", $page_val, $matches))
{
$match = $page_to;
break;
}

}

/*
* If we didn't match anything deliver a 404 or include our file
*/
if($match === NULL)
die("404");
else
require "pages/".$page_to;

?&gt;</pre>
<p>We’ve implemented friendly URLs in a simple way that is also very easy to work with in your script, we even have some basic validation that wouldn’t get relying on $_GET.</p>
<script type="text/javascript">
  addthis_url    = 'http%3A%2F%2Fhurricanesoftwares.edublogs.org%2F2008%2F06%2F24%2Ffriendly-urls-in-php-why-do-you-care%2F';
  addthis_title  = 'Friendly+URLs+in+PHP%3A+why+do+you+care%3F';
  addthis_pub    = '';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12" ></script>
]]></content:encoded>
			<wfw:commentRss>http://hurricanesoftwares.edublogs.org/2008/06/24/friendly-urls-in-php-why-do-you-care/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP: Securing Your Input Forms From MySQL Injection Attacks</title>
		<link>http://hurricanesoftwares.edublogs.org/2008/06/12/php-securing-your-input-forms-from-mysql-injection-attacks/</link>
		<comments>http://hurricanesoftwares.edublogs.org/2008/06/12/php-securing-your-input-forms-from-mysql-injection-attacks/#comments</comments>
		<pubDate>Thu, 12 Jun 2008 09:48:22 +0000</pubDate>
		<dc:creator>Ashish</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.hurricanesoftwares.com/?p=166</guid>
		<description><![CDATA[Every website has ‘em. Forms. Places for users to enter data into your website. Whether it be a search box, a “Contact Us” form, or variables in the website address, at some point in the flow of your script these suckers are going to touch your database. Oh, that’s no problem — We’ll just take [...]]]></description>
			<content:encoded><![CDATA[<p>Every website has ‘em. Forms. Places for users to enter data into your website. Whether it be a search box, a “Contact Us” form, or variables in the website address, at some point in the flow of your script these suckers are going to touch your database. Oh, that’s no problem — We’ll just take what they type in and run a query in MySQL on it!</p>
<p>WHOA, there! Are you sure you want to do that? Any input from a user should be treated like a nuclear fuel rod. You can handle it, but you’ve got to make sure you do it right. You wouldn’t just pick it up with your bare hands, would you?</p>
<p><strong>Why? Just what are MySQL Injection attacks anyway?</strong></p>
<p>Lets say your database has a table inside called ‘tbl_Users’. Inside ‘tbl_Users’ are a list of your users, which all have usernames, passwords, first names, last names, addresses, etc. If these users are presented with a login box somewhere on your site, your php user verification query might be something like this:</p>
<p><strong><em>SELECT * FROM `tbl_Users` WHERE `username`=&#8217;&#8221;.$_POST['username'].”‘ AND `password`=’”.md5($_POST['password']).”‘”</em></strong>The problem is that unscrupulous users (read: bad ones) could enter this into your form:</p>
<p> </p>
<p>username: no_onepassword: &#8216; OR &#8221;=&#8221;Which would make your query look something like this:</p>
<p>SELECT * FROM `tbl_Users` WHERE `username`=&#8217;no_one&#8217; AND `password`=&#8221; OR &#8221;=&#8221;Which, if you read that correctly, would allow that user access to whatever it was you wanted hidden by logging them in. There are a multitude of other ways this can be dangerous, but this is by far the easiest example. Even more unscrupulous users (read: the real jackasses) could send in multiple queries including DELETE queries.</p>
<p>In which case, when you wake up the morning after the attack you are most likely to be heard saying:”Hey, where did all my users go?” </p>
<p>Wow. Okay so I’ve got a friend… and his website isn’t secure. What can I do to help him out?</p>
<p>The good news is that with a few easy precautions, your “friend’s” website will be pretty secure against these types of attacks. I say pretty secure because there is no way to prevent every attack. We can only do our best to increase security to a point to take every realistic precaution to prevent these attacks.</p>
<p><strong>#1: Escape your variables!</strong></p>
<p>Using the php function ‘mysql_real_escape_string’ you can “escape” the single quote character from user input. This is probably the easiest method to prevent MySQL injection attacks. It works by adding a backslash (”\”) before each quote that the user enters into their input. So, to use our example from before:</p>
<p>username: hey&#8217;therebecomes</p>
<p>username: hey\&#8217;thereThis effectively stops MySQL injection in its tracks since it not only escapes the single quote (”‘”) character but also all other characters that the baddies can use to hijack your queries.</p>
<p>If you’ve got an array of data coming in, you can use this neat function that I found on the PHP mysql_real_escape_string page (code by “brian dot folts at gmail dot com”). It escapes all of the values in your array with ease.</p>
<p>To escape an array, use this function:</p>
<p><strong><em>function mysql_real_escape_array($t){<br />
return array_map(”mysql_real_escape_string”,$t);<br />
}</em></strong></p>
<p>Then you can call that function easily by passing your array to it:</p>
<p><strong><em>$your_array = mysql_real_escape_array($your_array);</em></strong></p>
<p><strong>#2: Check the variable type of your input.</strong></p>
<p>This is done by using the php functions “is_numeric()“, “is_string()“, “is_float()“, and “is_int()” to determine if the input the user is sending in is the same type that you were asking for. It’s not perfect, but if you were asking for a number and they sent in a word you know to discard it straight away and return an error thereby entirely avoiding any change of a MySQL injection attack.</p>
<p><strong>#3: Always use proper MySQL syntax, including “`” and “‘” characters.</strong></p>
<p>If your queries look something like this:</p>
<p><strong><em>SELECT * FROM tbl_Users WHERE username=$value; </em></strong>Rewrite it so that it looks more like this:</p>
<p><strong><em>$value = mysql_real_escape_string($value);mysql_query(SELECT * FROM `tbl_Users` WHERE `username`=&#8217;&#8221;.$value.&#8221;&#8216;&#8221;); </em></strong>Proper MySQL syntax requires that all table and field names are surrounded by the reverse apostraphe (”`”) and values surrounded with single quotes / apostraphe (”‘”).</p>
<p>I hope this gives you a better indication of what you can do to help secure your websites. Keep in mind that this is in no way a complete list. Be ever vigilant in your efforts to prevent attacks of any kind on your code. Leave a comment or two if this helped you at all or if you have different suggestions on how to secure your code from injection attacks!</p>
<script type="text/javascript">
  addthis_url    = 'http%3A%2F%2Fhurricanesoftwares.edublogs.org%2F2008%2F06%2F12%2Fphp-securing-your-input-forms-from-mysql-injection-attacks%2F';
  addthis_title  = 'PHP%3A+Securing+Your+Input+Forms+From+MySQL+Injection+Attacks';
  addthis_pub    = '';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12" ></script>
]]></content:encoded>
			<wfw:commentRss>http://hurricanesoftwares.edublogs.org/2008/06/12/php-securing-your-input-forms-from-mysql-injection-attacks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Calculating time by converting between time zones using PHP and PEAR</title>
		<link>http://hurricanesoftwares.edublogs.org/2008/05/15/calculating-time-by-converting-between-time-zones-using-php-and-pear/</link>
		<comments>http://hurricanesoftwares.edublogs.org/2008/05/15/calculating-time-by-converting-between-time-zones-using-php-and-pear/#comments</comments>
		<pubDate>Thu, 15 May 2008 11:46:45 +0000</pubDate>
		<dc:creator>Ashish</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.hurricanesoftwares.com/?p=162</guid>
		<description><![CDATA[PHP comes with an extensive catalog of date and time functions, all designed to let you easily retrieve temporal information, massage it into a format you require, and either use it in a calculation or display it to the user. However, if you&#8217;d like to do something more complicated, things get much, much hairier.
A simple [...]]]></description>
			<content:encoded><![CDATA[<p><strong>PHP comes with an extensive catalog of date and time functions, all designed to let you easily retrieve temporal information, massage it into a format you require, and either use it in a calculation or display it to the user. However, if you&#8217;d like to do something more complicated, things get much, much hairier.</strong></p>
<p>A simple example of this involves displaying the time on a Web page. With PHP, you can easily use the <em>date()</em> function to read the server&#8217;s clock and display the required information in a specific format. But what if you&#8217;d like to display the time in a different location &#8211; for example, if your company is located in a different country from your server and you want to see &#8220;home&#8221; time instead of local time? Well, then you have to figure out the difference between the two places and perform some date arithmetic to adjust for the different time zones. If the time difference is significant, you need to take account of whether the new time is on the day before or after, worry about daylight savings time, and keep track of end-of-the-month and leap year constraints.</p>
<p>As you can imagine, the math to perform such time zone conversions can quickly get very complicated if you do it manually. To be fair, PHP has built-in time zone functions to help with this, but these aren&#8217;t particularly intuitive and require a fair amount of time to get used to. A quicker alternative is to use the PEAR Date class, which comes with built-in support for time zones and is, by far, the simplest way to perform these conversions.</p>
<p>This tutorial will teach you how to convert temporal values between time zones with the PEAR Date class. It assumes that you have a working Apache and PHP installation and that the PEAR Date class has been correctly installed.</p>
<p><em><strong>Note: </strong>You can install the PEAR Date package directly from the Web, either by <a href="http://pear.php.net/package/Date" target="_blank">downloading</a> it or by using the <a href="http://pear.php.net/manual/en/installation.cli.php" target="_blank">instructions</a> provided.</em></p>
<h2>Getting started</h2>
<p>Let&#8217;s begin with the basics &#8211; initialising and using a Date object. Create a PHP script with the following lines of code:</p>
<pre>
getDate();
?&gt;
</pre>
<p>This is fairly simple &#8211; include the class code, initialise a Date() object with a date/time string, and then use the getDate() method to display the value you just inserted. Here&#8217;s the output:</p>
<p><b>2006-06-21 15:45:27</b></p>
<p>What if you want the date in a different format? If the format is a standard one, such as the ISO format, simply pass getDate() a modifier indicating this:</p>
<pre>
getDate(DATE_FORMAT_ISO_BASIC);
?&gt;
</pre>
<p>The output in this case conforms to the standard ISO format.</p>
<p><b>20060621T154527Z</b></p>
<p>If you&#8217;d like a custom format, you can do that too, with the format() method. Like PHP&#8217;s native date() function, this method accepts a series of format specifiers that indicate how each component of the date is to be formatted. Below is an example (look in the class documentation for a complete list of modifiers):</p>
<pre>
format("%A, %d %B %Y %T");
?&gt;
</pre>
<p>And here&#8217;s the output:</p>
<p><b>Wednesday, 21 June 2006 15:45:27</b></p>
<p><b>Converting between time zones</b></p>
<p>Now that you&#8217;ve got the basics, let&#8217;s talk about time zones. Once you have a Date() object initialised, converting from one time zone to another is a simple two-step process:</p>
<p>1. Tell the Date class which time zone you&#8217;re converting from, with the setTZByID() method.<br />
2. Then, tell the Date class which time zone you wish to convert to, with the convertTZByID() method.</p>
<pre>
setTZByID("GMT");

// convert to foreign time zone
$d-&gt;convertTZByID("IST");

// retrieve converted date/time
echo $d-&gt;format("%A, %d %B %Y %T");
?&gt;
</pre>
<p>In this case, I&#8217;m attempting to convert from Greenwich Mean Time (GMT) to Indian Standard Time (IST). India is about 5.5 hours ahead of Greenwich, which is why the output of the script is:</p>
<p><b>Wednesday, 21 June 2006 16:06:27</b></p>
<p>Simple, isn&#8217;t it? Here&#8217;s another example, this one demonstrating how the class handles leap years and month end values.</p>
<pre>

// include class
include ("Date.php");

// initialize object
$d = new Date("2008-03-01 06:36:27");

// set local time zone
$d-&gt;setTZByID("GMT");

// print local time
echo "Local time is " . $d-&gt;format("%A, %d %B %Y %T") . "\n";

// convert to foreign time zone
$d-&gt;convertTZByID("PST");

// retrieve converted date/time
echo "Destination time is " . $d-&gt;format("%A, %d %B %Y %T");
?&gt;
</pre>
<p>And the output is:</p>
<p><b>Local time is Saturday, 01 March 2008 06:36:27<br />
Destination time is Friday, 29 February 2008 22:36:27</b></p>
<p>Note: In case you&#8217;re wondering where the time zone IDs come from, you can find a complete list within the class documentation.</p>
<p><b>Calculating GMT offsets</b></p>
<p>Another piece of information that&#8217;s sometimes useful when working with time zones is the GMT offset &#8212; that is, the difference between the specified time zone and standard GMT. The PEAR Date class lets you get this information easily, via its getRawOffset() method. Here&#8217;s an example:</p>
<pre>
setTZByID("PST");

// get raw offset from GMT, in msec
echo $d-&gt;tz-&gt;getRawOffset();
?&gt;
</pre>
<p>Here, the getRawOffset() method calculates the time difference between the local time and GMT. Here&#8217;s the output:</p>
<p><b>-28800000</b></p>
<p>Note that this offset value is expressed in milliseconds, so you will need to divide it by 3600000 (the number of milliseconds in one hour) to calculate the time zone difference in hours.</p>
<p>Tip: You can use the inDaylightTime() method to see if the destination is currently observing daylight savings time. Look in the class documentation for details on this method.<br />
Adding and subtracting timespans</p>
<p>The Date class also lets you perform sophisticated date arithmetic on temporal values, adding or subtracting durations to a date/time value. These durations (or timespans) are expressed as a string containing day, hour, minute and/or second components.</p>
<pre>
addSpan(new Date_Span("0,1,20,0"));

// retrieve date as formatted string
echo $d-&gt;format("%A, %d %B %Y %T");
?&gt;
</pre>
<p>In this case, I&#8217;ve added an hour and twenty minutes to the initial timestamp, by calling the Date class&#8217; addSpan() method and supplying it with a Date_Span() object initialised to that duration. The output is fairly easy to guess:</p>
<p><b>Wednesday, 21 June 2006 17:05:27</b></p>
<p>Just as you can add timespans, so too can you subtract them. That, in fact, is the purpose of the subtractSpan() method, which is illustrated below.</p>
<pre>
addSpan(new Date_Span("0,1,20,0"));

// subtract 00:05 from it
$d-&gt;subtractSpan(new Date_Span("0,0,5,0"));

// retrieve date as formatted string
echo $d-&gt;format("%A, %d %B %Y %T");
?&gt;
</pre>
<p>Here, I&#8217;ve first added an hour and twenty minutes, and then subtracted a further five minutes. The net effect is an addition of an hour and fifteen minutes, and the output reflects this:</p>
<p><b>Wednesday, 21 June 2006 17:00:27</b></p>
<p>As the examples above illustrate, the PEAR Date class provides methods to intuitively and efficiently perform fairly complex date math. If you&#8217;re looking for a stress-free way to convert timestamps between different locations, I&#8217;d heartily recommend it to you.</p>
<script type="text/javascript">
  addthis_url    = 'http%3A%2F%2Fhurricanesoftwares.edublogs.org%2F2008%2F05%2F15%2Fcalculating-time-by-converting-between-time-zones-using-php-and-pear%2F';
  addthis_title  = 'Calculating+time+by+converting+between+time+zones+using+PHP+and+PEAR';
  addthis_pub    = '';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12" ></script>
]]></content:encoded>
			<wfw:commentRss>http://hurricanesoftwares.edublogs.org/2008/05/15/calculating-time-by-converting-between-time-zones-using-php-and-pear/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>10 reasons to use PEAR classes</title>
		<link>http://hurricanesoftwares.edublogs.org/2008/05/15/10-reasons-to-use-pear-classes/</link>
		<comments>http://hurricanesoftwares.edublogs.org/2008/05/15/10-reasons-to-use-pear-classes/#comments</comments>
		<pubDate>Thu, 15 May 2008 11:13:01 +0000</pubDate>
		<dc:creator>Ashish</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.hurricanesoftwares.com/?p=159</guid>
		<description><![CDATA[Most PHP Web developers have heard of PEAR, the PHP Extension and Application Repository, but very few of them actually use it on a regular basis. Here are 10 reasons to get started today.
Most PHP Web developers have heard of PEAR, the PHP Extension and Application Repository, but very few of them actually use it [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Most PHP Web developers have heard of PEAR, the PHP Extension and Application Repository, but very few of them actually use it on a regular basis. Here are 10 reasons to get started today.</strong></p>
<p>Most PHP Web developers have heard of PEAR, the PHP Extension and Application Repository, but very few of them actually use it on a regular basis. This is an oversight that should be corrected, because PEAR is actually a rich treasure trove of PHP widgets that can significantly simplify the average Web developer&#8217;s workday.</p>
<p>If you think I&#8217;m overstating the benefits, ask yourself if you&#8217;ve ever written custom code to (a) create HTML e-mail, (b) generate Web forms on the fly, or (c) validate email addresses. PEAR has pre-built PHP packages for all these tasks, and a few hundred more besides. These packages provide a robust, well-tested code base that can save you the time and effort you would otherwise spend on &#8220;rolling your own&#8221; code. You can&#8217;t beat the price either&#8230;they&#8217;re free!</p>
<p>PEAR classes cover a wide range of tasks, and so this document will focus specifically on classes of interest to developers working with Web pages and form input. If there are other categories you&#8217;d like to see addressed, send in your suggestions and we will examine those areas too&#8230;and until then, here&#8217;s to easier coding!</p>
<p><strong>Note:</strong> You can install PEAR packages directly from the Web, by following the provided instructions.</p>
<p><strong>Package Name: Validate</strong><br />
<strong>Description:</strong> This package provides validation routines for common input types: email addresses, credit card numbers, URLs, dates and times, string and number classes, and more.</p>
<p><em>Use this package to test user input entered in Web forms and ensure it is valid before using it in a calculation/saving it to a file or database.</em></p>
<p><strong>URL:</strong> <a href="http://pear.php.net/package/Validate" target="_blank">http://pear.php.net/package/Validate</a></p>
<p><strong>Calendar</strong><br />
This package creates calendar data structures for one or more months. These data structures can then be combined with HTML formatting or a template to create a calendar display, complete with forward/backward navigation links.</p>
<p><em>Use this package to quickly integrate a pop-up Web calendar into a Web site.</em></p>
<p><a href="http://pear.php.net/package/Calendar" target="_blank">http://pear.php.net/package/Calendar</a></p>
<p><strong>Mail_Mime</strong><br />
This package provides routines to create a MIME-compliant multi-part message. Such a message can contain embedded HTML, images, file attachments, or other parts. The package also provides functions to decode received multi-part messages into their constituent parts.</p>
<p><em>Use this package to create HTML email with embedded images, or messages with one or more attachments. You can also use this class to decode multi-part messages &#8211; for example, as an attachment browser in a Web mail client.</em></p>
<p><a href="http://pear.php.net/package/Mail_Mime" target="_blank">http://pear.php.net/package/Mail_Mime</a></p>
<p><strong>Cache</strong><br />
This package provides a simple caching framework for a Web site. It allows you to cache the output of PHP scripts as well as function calls, and reduce response times by rendering the cached pages to clients. Cached pages may be stored as files on disk, in a database, or using a custom storage engine.</p>
<p><em>If your site receives a lot of traffic, use this package to reduce server load and page processing time by occasionally providing clients with snapshots from the page cache instead of the &#8220;live&#8221; page. You can also reduce the load on your database server by caching the output of frequently-used SQL queries.</em></p>
<p><a href="http://pear.php.net/package/Cache" target="_blank">http://pear.php.net/package/Cache</a></p>
<p><strong>Image_Graph</strong><br />
This package makes it possible to automatically convert numerical data into a graph suitable for display on a Web page. Bar, graph, pie, radar and scatter graphs are just some of the supported graph types. X and Y axis customisations are supported, as are many different output formats.</p>
<p><em>Use this package to display numerical data in a visual manner for easier comprehension &#8211; for example, when calculating Web site traffic or ad clicks.</em></p>
<p><a href="http://pear.php.net/package/Image_Graph" target="_blank">http://pear.php.net/package/Image_Graph</a></p>
<p><strong>HTML_QuickForm</strong><br />
This package provides routines to generate, validate, and process Web forms programmatically. It supports all the HTML form input types, and comes with built-in validation routines for most common input types. It also provides built-in functionality for multi-page forms and file upload forms.</p>
<p><em>Use this package to significantly simplify the task of generating Web forms at run-time, or to efficiently validate and process form input.</em></p>
<p><a href="http://pear.php.net/package/HTML_QuickForm" target="_blank">http://pear.php.net/package/HTML_QuickForm</a></p>
<p><strong>Auth</strong><br />
This package provides a framework for a basic login/authentication system using PHP. It can verify user credentials against a variety of data sources, including MySQL databases, ASCII files, LDAP servers and POP3 servers.</p>
<p><em>Use this package to quickly create a login system for a Web application. Because it has &#8220;out of the box&#8221; support for so many authentication sources, it can also be used to implement Web-based &#8220;single login&#8221; infrastructure.</em></p>
<p><a href="http://pear.php.net/package/Auth" target="_blank">http://pear.php.net/package/Auth</a></p>
<p><strong>XML_RSS</strong><br />
This package is designed to parse RSS documents. It extracts information from an RSS feed as PHP data structures, which can be processed and formatted for display.</p>
<p><em>Use this package to integrate RSS feeds from other sites into your Web pages.</em></p>
<p><a href="http://pear.php.net/package/XML_RSS" target="_blank">http://pear.php.net/package/XML_RSS</a></p>
<p><strong>HTML_Progress</strong><br />
This package provides a framework for a progress bar on a Web site. It uses PHP, JavaScript and CSS to display and dynamically update a progress bar with visual notification of a task&#8217;s progress.</p>
<p><em>Use this package to display progress bars for time-consuming Web tasks &#8212; for example a file upload or a long-running loop.</em></p>
<p><a href="http://pear.php.net/package/HTML_Progress" target="_blank">http://pear.php.net/package/HTML_Progress</a></p>
<p><strong>Translation</strong><br />
This package provides a framework for multi-lingual Web sites. It contains routines to retrieve a translation for each string value from a database and insert it into the appropriate location on each translation-enabled page.</p>
<p><em>Use this package to efficiently handle multi-language versions of a Web site.</em></p>
<p><a href="http://pear.php.net/package/Translation/" target="_blank">http://pear.php.net/package/Translation/</a></p>
<script type="text/javascript">
  addthis_url    = 'http%3A%2F%2Fhurricanesoftwares.edublogs.org%2F2008%2F05%2F15%2F10-reasons-to-use-pear-classes%2F';
  addthis_title  = '10+reasons+to+use+PEAR+classes';
  addthis_pub    = '';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12" ></script>
]]></content:encoded>
			<wfw:commentRss>http://hurricanesoftwares.edublogs.org/2008/05/15/10-reasons-to-use-pear-classes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Running XPath queries in PHP</title>
		<link>http://hurricanesoftwares.edublogs.org/2008/05/15/running-xpath-queries-in-php/</link>
		<comments>http://hurricanesoftwares.edublogs.org/2008/05/15/running-xpath-queries-in-php/#comments</comments>
		<pubDate>Thu, 15 May 2008 10:56:55 +0000</pubDate>
		<dc:creator>Ashish</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.hurricanesoftwares.com/?p=158</guid>
		<description><![CDATA[XPath is a language that allows you to address parts of an XML document, making XSLT transformations practically necessary. It also makes it an invaluable tool for managing XML data in applications such as Web applications.
Microsoft provides XPath functionality through the selectSingleNode() and selectNodes() methods on DOM nodes and documents. However, PHP uses functions that [...]]]></description>
			<content:encoded><![CDATA[<p>XPath is a language that allows you to address parts of an XML document, making XSLT transformations practically necessary. It also makes it an invaluable tool for managing XML data in applications such as Web applications.</p>
<p>Microsoft provides XPath functionality through the selectSingleNode() and selectNodes() methods on DOM nodes and documents. However, PHP uses functions that provide XPath functionality through contexts. In the following example, I&#8217;ll show sample XML data and PHP code to grab different parts of the XML document. I&#8217;ll also explain how the PHP code works.</p>
<p>In the example code, I use the following XML data to provide the functionality. (Note: This code was developed and run successfully using PHP 4.3.4, Windows XP, and IIS 5.1.)</p>
<pre>

Marmaduke
Garfield

Snoopy
Heathcliff

Spike
Sylvester
</pre>
<p>This XML data contains a few elements and some attributes including a namespace declaration &#8212; some basic XML. This results in varied queries for me to test.</p>
<pre>
&lt;?php
$sxml = '

            Marmaduke
            Garfield

            Snoopy
            Heathcliff

            Spike
            Sylvester

    ';

$xml = domxml_open_mem($sxml);

$xpc = xpath_new_context($xml);
xpath_register_ns($xpc, "x", "http://www.someplace.com");

$nodes = xpath_eval($xpc, "//x:row/x:dog[@color='yellow']/text()");
foreach ($nodes-&gt;nodeset as $node) {
    print $node-&gt;content . "\n";
}

$nodes = xpath_eval($xpc, "//x:row/x:dog");
foreach ($nodes-&gt;nodeset as $node) {
    print $xml-&gt;dump_node($node) . "\n";
}

$nodes = xpath_eval($xpc, "//x:cat/child::text()|//x:dog[@color='white' or
@color='gray']/text()");
foreach ($nodes-&gt;nodeset as $node) {
    print $node-&gt;content . "\n";
}

$xml-&gt;free();
?&gt;
</pre>
<p>First, I create a local variable to hold the XML string. This information could have been passed in as part of a POST HTTP request. However, for this example, I&#8217;m going to include it in the code. The next step is to create a DOM Document by using the domxml_open_mem() function. This function creates a DOM Document object in memory from a valid XML string. It accepts one parameter: the XML string. Another way to accomplish this is to store the XML in a separate file and use the domxml_open_file() function to load the XML from a file. This function takes one parameter: the filename of the XML file.</p>
<p>Once I create the DOM Document object, I can create an XPath context with this object through the xpath_new_context() function, which takes one parameter: the current DOM Document object. This context is used to evaluate the XPath expression and is also used to register namespaces, if needed. Since my XML includes a namespace, I register the namespace with the xpath_register_ns() function. This makes it possible to create XPath queries using prefixes. The xpath_register_ns() function takes three parameters: the XPath context, the prefix, and the namespace, respectively.</p>
<p>Now I can run XPath queries. This is done with the xpath_eval() function, whose first parameter is the XPath context and second parameter is the XPath expression. The function returns an array of DOM Nodes. In my code, I step through the nodeset and produce some form of output.</p>
<p>In the first XPath example, I grab all the x:dog text elements under the x:row nodes, where the &#8216;color&#8217; attribute equals &#8216;yellow&#8217;. This is where the XPath expression in PHP differs slightly from an XPath expression using MSXML. I include the &#8216;/text()&#8217; part of the expression to return the text nodes only. With MSXML, you access the text node with the &#8216;text&#8217; property. Using the &#8216;content&#8217; property on the returned text node, I can get the content of the text node.</p>
<p>In the second example, I grab all the x:dog elements under the x:row nodes. However, I use the dump_node() method on the DOM Document object to print out the complete XML of the appropriate node. The dump_node() method accepts one parameter: the DOM Node of which you wish to dump the contents.</p>
<p>In the last example, I grab all the x:cat text nodes and all the x:dog text nodes where the &#8216;color&#8217; attribute is &#8216;white&#8217; or &#8216;gray&#8217;. Once again, I step through the nodeset and print out the content of each text node. Finally, I free up the DOM Document object.</p>
<script type="text/javascript">
  addthis_url    = 'http%3A%2F%2Fhurricanesoftwares.edublogs.org%2F2008%2F05%2F15%2Frunning-xpath-queries-in-php%2F';
  addthis_title  = 'Running+XPath+queries+in+PHP';
  addthis_pub    = '';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12" ></script>
]]></content:encoded>
			<wfw:commentRss>http://hurricanesoftwares.edublogs.org/2008/05/15/running-xpath-queries-in-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Mapping visitors&#8217; IP addresses in PHP</title>
		<link>http://hurricanesoftwares.edublogs.org/2008/05/15/mapping-visitors-ip-addresses-in-php/</link>
		<comments>http://hurricanesoftwares.edublogs.org/2008/05/15/mapping-visitors-ip-addresses-in-php/#comments</comments>
		<pubDate>Thu, 15 May 2008 09:05:02 +0000</pubDate>
		<dc:creator>Ashish</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.hurricanesoftwares.com/?p=156</guid>
		<description><![CDATA[Sometimes you just need to know what country your site visitors are coming from—for example, if you&#8217;re trying to implement geo-targeted advertising. This article will show you how. 
Sometimes you just need to know what country your site visitors are coming from—for example, if you&#8217;re trying to implement geo-targeted advertising. That&#8217;s where a tool like [...]]]></description>
			<content:encoded><![CDATA[<p><span class="smdeck">Sometimes you just need to know what country your site visitors are coming from—for example, if you&#8217;re trying to implement geo-targeted advertising. This article will show you how. </span></p>
<p>Sometimes you just need to know what country your site visitors are coming from—for example, if you&#8217;re trying to implement geo-targeted advertising. That&#8217;s where a tool like MaxMind&#8217;s GeoIP comes in—it lets you easily extract geographic data from your visitor&#8217;s IP address.</p>
<p>MaxMind makes available both commercial and free databases; the commercial ones are extremely precise and can get as fine-grained as the user&#8217;s city, while the free version can only identify the country of origin. We&#8217;ll use the free version in this article. If you need more detailed information, such as the remote client&#8217;s city and state of origin, you will need to purchase a more detailed database from <a title="link" href="http://www.maxmind.com/" target="_blank">MaxMind</a>.</p>
<p><span class="subhead1">Getting started</span><br />
To use it, you&#8217;ll have to first download the <a href="http://www.maxmind.com/app/geoip_country" target="_blank">GeoIP Free Country file</a> and extract it into a directory in your Web server. Then you&#8217;ll have to pick which language API to use with the database file. For simplicity, we&#8217;re going to use the pure PHP version because it doesn&#8217;t require any additional configuration or Apache modules. Remember to read the <a title="link" href="http://www.maxmind.com/download/geoip/database/LICENSE.txt" target="_blank">license terms</a> before installing these on your Web site to ensure you are in compliance.</p>
<p>The code below<strong></strong> demonstrates the basics of using the module (geoip.inc) to access the GeoIP Free Country database (GeoIP.dat). The example assumes both the PHP include and the country database file are in the same directory as the PHP file itself. You&#8217;ll have to change the paths as needed if this is not the case in your installation.</p>
<pre>
</pre>
<p>The sample code is pretty straightforward. After including the GeoIP PHP function library, the first step is to open the GeoIP database file with the geoip_open() function. This function accepts two arguments: the path to the database file and the type of database.</p>
<p>We then use the handle returned by the call to geoip_open() to obtain the two-letter country code and human-friendly name corresponding to the given IP address, via the geoip_country_code_by_addr() and geoip_country_code_by_name() functions, respectively. Both functions accept two arguments: the handle returned by geoip_open() and the IP address to resolve.</p>
<p>Once the required information is obtained, we close the database file with a call to geoip_close(). Simple as that.</p>
<script type="text/javascript">
  addthis_url    = 'http%3A%2F%2Fhurricanesoftwares.edublogs.org%2F2008%2F05%2F15%2Fmapping-visitors-ip-addresses-in-php%2F';
  addthis_title  = 'Mapping+visitors%26%238217%3B+IP+addresses+in+PHP';
  addthis_pub    = '';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12" ></script>
]]></content:encoded>
			<wfw:commentRss>http://hurricanesoftwares.edublogs.org/2008/05/15/mapping-visitors-ip-addresses-in-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PHP Templating with Smarty</title>
		<link>http://hurricanesoftwares.edublogs.org/2008/03/21/php-templating-with-smarty/</link>
		<comments>http://hurricanesoftwares.edublogs.org/2008/03/21/php-templating-with-smarty/#comments</comments>
		<pubDate>Fri, 21 Mar 2008 06:25:55 +0000</pubDate>
		<dc:creator>Ashish</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://hurricanesoftwares.edublogs.org/2008/03/21/php-templating-with-smarty/</guid>
		<description><![CDATA[Smarty Overview
The theoretical web development process is that: first the designer makes the interface, and breaks it down into HTML pieces for the programmer then the programmer implements the PHP business logic into the HTML.
That&#8217;s fine in theory, but in practice, from my experience, the client frequently comes with more requirements, or maybe more modifications [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Smarty Overview</strong><br />
The theoretical web development process is that: first the designer makes the interface, and breaks it down into HTML pieces for the programmer then the programmer implements the PHP business logic into the HTML.</p>
<p>That&rsquo;s fine in theory, but in practice, from my experience, the client frequently comes with more requirements, or maybe more modifications to the design or to the business logic. When this happens , the HTML is modified (or words rebuilt ) programmer changes the code inside HTML.</p>
<p>The problem with this scenario is that the programmer needs to be on stand-by until the designer completes the layout and the HTML files. Another problem is that if there is a major design change then the programmer will change the code to fit in the new page. And that&rsquo;s why I recommand Smarty. Smarty is a templating engine for PHP.</p>
<p>You can download it from <a href="http://www.phpinsider.com/php/code/Smarty/" target="_blank">http://www.phpinsider.com/php/code/Smarty/</a> or <a href="http://smarty.php.net" target="_blank">http://smarty.php.net</a> . The installation process is very simple. Just read the documentation and follow up the instructions.</p>
<p>So what is Smarty ? Smarty is a set of PHP classes that compile the templates into PHP scripts. Smarty is a template language and a very useful tool for designers and programmers.</p>
<p><strong>Smarty for Designers</strong></p>
<p>Designers work with HTML files. To work with Smarty, you work with template files. These files are are made up of static content but combined with Smarty mark-up tags. All the template files have a .tpl extension. The Smarty template tags are enclosed within { and } delimiters.</p>
<p>Let&rsquo;s consider the basic structure of a web page. There is a header, a middle part, and a footer. A template file that includes the header and the footer looks like this:</p>
<p>{include file=&quot;header.tpl&quot;}<br />
&lt;form name=&quot;form1&quot;&gt;<br />
&nbsp;&nbsp;&nbsp; Label1 &lt;input type=&quot;text&quot; name=&quot;text1&quot;&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;input type=&quot;submit&quot; value=&quot;submit&quot;&gt;<br />
&lt;/form&gt;<br />
{include file=&quot;footer.tpl&quot;}</p>
<p>All the templates should reside in a single template directory. After calling a template for the first time, the compiled template will reside in templates_c.</p>
<p>Smarty language is very poweful. All the variables that come from PHP are identified in Smarty with {$Variable_Name} (we precede them with a $ sign). So if we have a variable in PHP that is called $MyName, then to print it in Smarty you have to write something like:</p>
<p>
&lt;html&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;body&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Welcome, {$MyName} &lt;br&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;/body&gt;<br />
&lt;/html&gt;</p>
<p>The power of Smarty lies also in its flexibility. You can insert IFs and LOOPs into the template. The syntax for IF is:</p>
<p>{if &lt;condition&gt; }<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; html code<br />
{else}<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; html code<br />
{/if}</p>
<p>Let&rsquo;s say you have a dynamic menu based on links. Depending on the link you click, you go to a specific page. So you get from PHP a variable $Menu with a integer value, depending on the page you are. The template looks like :</p>
<p>{if ($Menu == 1) }<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Option 1 <br />
{else}<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;a href=&quot;option1.php&quot;&gt;Option 1&lt;/a&gt;<br />
{/if}<br />
{if ($Menu == 2)}<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Option 2<br />
{else}<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;a href=&quot;option2.php&quot;&gt;Option 2&lt;/a&gt;<br />
{/if}</p>
<p>For coding a loop let&rsquo;s suppose you get an array like the following from PHP :</p>
<p>&lt;table&gt;<br />
&lt;tr <br />
{section name=user loop=$userID}<br />
{if $smarty.section.user.iteration is odd}<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; bgcolor=#efefef<br />
{else}<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; bgcolor=#ffffff&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
{/if} <br />
&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;td&gt;&nbsp;&nbsp;&nbsp; ID = {$userID[user]}&nbsp; &lt;/td&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;td&gt; Name = {$name[user]}&nbsp;&nbsp;&nbsp;&nbsp; &lt;/td&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;td&gt; Address = {$address[user]} &lt;/td&gt;<br />
&lt;/tr&gt;<br />
&nbsp;&nbsp;&nbsp; {sectionelse}<br />
&lt;tr&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;td&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; There is no user.<br />
&nbsp;&nbsp;&nbsp; &lt;/td&gt;<br />
&lt;/tr&gt;<br />
&lt;/section&gt;<br />
&lt;/table&gt;</p>
<p>Iteration is an internal counter for Smarty. It helps us to know the current iteration of the section. I use this internal variable to make alternate row colors in the table by checking if current iteration value is odd or not (Note that iteration was added to Smarty from version 1.4.4).</p>
<p>An alternative for LOOPS is FOREACH which is used to loop over a single associative array.</p>
<p>&lt;foreach from=$users item=current_user&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Name = {$current_user}<br />
&lt;foreachelse}<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; No user available.<br />
&lt;/foreach&gt;</p>
<p>The main difference between SECTION and FOREACH is that for SECTION you can start from a specific value, and can also set a step for the iteration, whereas for FOREACH you have to loop over all values.</p>
<p><strong>Smarty for Programmers</strong></p>
<p>The advantage for programmers is that they write the code in a PHP file without having to mix the instructions with HTML. Furthermore, if the designer changes the layout of a page the programmer doesn&rsquo;t have to change the code to suit the new layout since the functionalities won&rsquo;t change. You do your work in your files, assign to the templates all the values needed to print on the site and go out for a beer. You won&rsquo;t get phone calls asking you to change a bit of code because the designer changed the layout and now a set of internal errors cropped up.</p>
<p>In the PHP file you need to include the Smarty class require &lsquo;Smarty.class.php&#8217;. After that you need to instantiate the smarty with $smarty = new Smarty.</p>
<p>To assign a variable to the template you need to $smarty-&gt;assign(&#8217;UserName&#8217;, &lsquo;John Doe&rsquo;). After everything is finished you call the method to display the template $smarty-&gt;display(&#8217;index.tpl&#8217;).</p>
<p>A sample code looks like this (index.php) :</p>
<p>&lt;?php<br />
require &#8216;Smarty.class.php&#8217;;<br />
$smarty = new Smarty;</p>
<p>$smarty-&gt;assign(&#8217;Username&#8217;, &#8216;John Doe&#8217;);<br />
$smarty-&gt;display(&#8217;index.tpl&#8217;);<br />
?&gt;</p>
<p>The template (index.tpl) looks like this:</p>
<p>&lt;html&gt;<br />
&lt;body&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Welcome {$Username}<br />
&lt;/body&gt;<br />
&lt;/html&gt;</p>
<p>
You can also create an array in PHP an pass it to the template:</p>
<p>$tmp = array ( &#8216;UID&#8217;=&gt; &#8216;10&#8242;,&nbsp; &amp;&#8217;Name&#8217; =&gt; &#8216;John Doe&#8217;, &#8216;Address&#8217;=&gt;&#8217;Home address&#8217;);<br />
$smarty-&gt;assign(&#8217;info&#8217;, $tmp);</p>
<p>
<strong>Sample Script</strong></p>
<p>This script connects to a local database and select all the products from the &lsquo;Products&rsquo; table. Then it passes all the values to the template, which prints them on the screen.</p>
<p><strong>INDEX.PHP</strong></p>
<p>&lt;?php<br />
require &#8216;Smarty.class.php&#8217;;<br />
$smarty = new Smarty;</p>
<p>$hostname = &quot;localhost&quot;;<br />
$dbUser = &quot;sqluser&quot;;<br />
$dbPass = &quot;sqlpass&quot;;<br />
$dbName = &quot;sqldb&quot;;<br />
// connect to the database<br />
$conn = mysql_connect($hostname, $dbUser, $dbPass) or die(&quot;Cannot connect to the database&quot;);</p>
<p>mysql_select_db($dbName);</p>
<p>$sql = &quot;SELECT prodID, info FROM products ORDER BY prodID ASC&quot;;<br />
// get all the products from the table<br />
$res = mysql_query($sql);<br />
$results = array();<br />
$i=0;<br />
while ($r=mysql_fetch_array($res)) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $tmp = array(<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#8216;prodID&#8217; =&gt; $r['prodID'],<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#8216;info&#8217;=&gt; $r['info']<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; );<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $results[$i++] = $tmp;<br />
}<br />
// pass the results to the template<br />
$smarty-&gt;assign(&#8217;results&#8217;, $results);<br />
// load the template<br />
$smarty-&gt;display(&#8217;index.tpl&#8217;);<br />
?&gt;</p>
<p>
<strong>INDEX.TPL</strong></p>
<p>&lt;html&gt;<br />
&lt;body&gt;<br />
Here&#8217;s a table with the results: &lt;br&gt;<br />
&lt;table cellpadding=1 cellspacing=0 border=0 width=100%&gt;<br />
{section name=nr loop=$results}<br />
&nbsp;&nbsp;&nbsp; &lt;tr {if $smarty.section.nr.iteration is odd} bgcolor=&quot;#efefef&quot;{/if}&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;td class=fb width=15%&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;nobr&gt;&lt;a href=&#8221;show-product.php?id={$results[nr].prodID}&quot;&gt;Press here&lt;/a&gt;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;td class=fb width=29%&gt;&lt;a href=&quot;show.php?id={$results[nr].prodID}&quot;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {popup inarray=$smarty.section.nr.iteration}<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &gt;{$results[nr].info}&lt;/a&gt;&lt;/td&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;/tr&gt;</p>
<p>{sectionelse}<br />
&lt;tr&gt;&lt;td align=&quot;center&quot;&gt;&lt;br&gt;&lt;b&gt;no product &lt;/b&gt; &lt;br&gt; &lt;/td&gt;&lt;/tr&gt;<br />
{/section}<br />
&nbsp;&nbsp;&nbsp; <br />
&lt;/table&gt;</p>
<p>&lt;br&gt;</p>
<p>Here&#8217;s a select with the results: &lt;br&gt;<br />
&lt;select name=&quot;mys&quot;&gt;<br />
&nbsp;&nbsp;&nbsp; {section name=nr loop=$results}<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;option value=&quot;{$results[nr].prodID}&quot;&gt;{$results[nr].info}&lt;/option&gt;<br />
&nbsp;&nbsp;&nbsp; {/section}<br />
&lt;/select&gt;</p>
<p>&lt;/body&gt;<br />
&lt;/html&gt;</p>
<p><strong>Summary</strong></p>
<p>Smarty is a great tool for both designers and developers. By using Smarty you can reduce the site development and maintenance times. If you are a developer you no longer need to mix PHP code with HTML code. Just take care of business logic and leave the HTML to the designer.</p>
<script type="text/javascript">
  addthis_url    = 'http%3A%2F%2Fhurricanesoftwares.edublogs.org%2F2008%2F03%2F21%2Fphp-templating-with-smarty%2F';
  addthis_title  = 'PHP+Templating+with+Smarty';
  addthis_pub    = '';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12" ></script>
]]></content:encoded>
			<wfw:commentRss>http://hurricanesoftwares.edublogs.org/2008/03/21/php-templating-with-smarty/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PEAR : PHP Extension and Application Repository</title>
		<link>http://hurricanesoftwares.edublogs.org/2008/03/21/pear-php-extension-and-application-repository/</link>
		<comments>http://hurricanesoftwares.edublogs.org/2008/03/21/pear-php-extension-and-application-repository/#comments</comments>
		<pubDate>Fri, 21 Mar 2008 06:09:36 +0000</pubDate>
		<dc:creator>Ashish</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://hurricanesoftwares.edublogs.org/2008/03/21/pear-php-extension-and-application-repository/</guid>
		<description><![CDATA[The PHP Extension and Application Repository, or PEAR, is a framework and distribution system for PHP code components. The PEAR project seeks to provide a structured library of code, maintain a system for distributing code and for managing code packages, and promote a standard coding style. Though community-driven, the PEAR project has a PEAR Group [...]]]></description>
			<content:encoded><![CDATA[<p>The <strong>PHP Extension and Application Repository</strong>, or <strong>PEAR,</strong> is a framework and distribution system for PHP code components. The PEAR project seeks to provide a structured library of code, maintain a system for distributing code and for managing code packages, and promote a standard coding style. Though community-driven, the PEAR project has a PEAR Group which serves as the governing body and takes care of administrative tasks. Each PEAR code package comprises an independent project under the PEAR umbrella. It has its own development team, versioning-control and documentation.</p>
<p>A PEAR package is distributed as a gzipped tar file. It can consist of source code or binaries or both. Many PEAR packages can readily be used by developers as ordinary third party code via simple include statements in PHP. More elegantly, the PEAR installer which comes with PHP by default may be used to install PEAR packages so that the extra functionality provided by the package appears as an integrated part of the PHP installation. Unlike the Comprehensive Perl Archive Network (CPAN) archives, which PEAR took as its model, PEAR packages do not have implicit dependencies so that a package&#8217;s placement in the PEAR package tree does not relate to code dependencies. Rather, PEAR packages must explicitly declare all dependencies on other PEAR packages.</p>
<p>The PEAR base classes contain code for simulating object-oriented destructors and consistent error-handling. Packages exist for many basic PHP functions including authentication, caching, database access, encryption, configuration, HTML, web services and XML.</p>
<p><strong>PECL (PHP Extension Community Library) </strong>is conceptually very similar to PEAR, and indeed PECL modules are installed with the PEAR Package Manager. PECL contains C extensions for compiling into PHP. As C programs , PECL extensions run more efficiently than PEAR packages. PECL includes modules for XML-parsing, access to additional databases, mail-parsing, embedding Perl or Python in PHP scripts and for compiling PHP scripts. Originally PECL was called the PEAR Extension Code Library, but it now operates independently of PEAR.</p>
<p><strong>List of package categories</strong></p>
<p>&nbsp;&nbsp;&nbsp; * Authentication<br />
&nbsp;&nbsp;&nbsp; * Benchmarking<br />
&nbsp;&nbsp;&nbsp; * Caching<br />
&nbsp;&nbsp;&nbsp; * Configuration<br />
&nbsp;&nbsp;&nbsp; * Console<br />
&nbsp;&nbsp;&nbsp; * Database<br />
&nbsp;&nbsp;&nbsp; * Date &amp; Time<br />
&nbsp;&nbsp;&nbsp; * Encryption<br />
&nbsp;&nbsp;&nbsp; * Event<br />
&nbsp;&nbsp;&nbsp; * File Formats<br />
&nbsp;&nbsp;&nbsp; * File System<br />
&nbsp;&nbsp;&nbsp; * Gtk Components<br />
&nbsp;&nbsp;&nbsp; * Gtk2 Components<br />
&nbsp;&nbsp;&nbsp; * HTML<br />
&nbsp;&nbsp;&nbsp; * HTTP<br />
&nbsp;&nbsp;&nbsp; * Images<br />
&nbsp;&nbsp;&nbsp; * Internationalization<br />
&nbsp;&nbsp;&nbsp; * Logging<br />
&nbsp;&nbsp;&nbsp; * Mail<br />
&nbsp;&nbsp;&nbsp; * Math<br />
&nbsp;&nbsp;&nbsp; * Networking<br />
&nbsp;&nbsp;&nbsp; * Numbers<br />
&nbsp;&nbsp;&nbsp; * Payment<br />
&nbsp;&nbsp;&nbsp; * PEAR<br />
&nbsp;&nbsp;&nbsp; * PHP<br />
&nbsp;&nbsp;&nbsp; * Processing<br />
&nbsp;&nbsp;&nbsp; * Science<br />
&nbsp;&nbsp;&nbsp; * Semantic Web<br />
&nbsp;&nbsp;&nbsp; * Streams<br />
&nbsp;&nbsp;&nbsp; * Structures<br />
&nbsp;&nbsp;&nbsp; * System<br />
&nbsp;&nbsp;&nbsp; * Text<br />
&nbsp;&nbsp;&nbsp; * Tools and Utilities<br />
&nbsp;&nbsp;&nbsp; * Validate<br />
&nbsp;&nbsp;&nbsp; * Web Services<br />
&nbsp;&nbsp;&nbsp; * XML</p>
<script type="text/javascript">
  addthis_url    = 'http%3A%2F%2Fhurricanesoftwares.edublogs.org%2F2008%2F03%2F21%2Fpear-php-extension-and-application-repository%2F';
  addthis_title  = 'PEAR+%3A+PHP+Extension+and+Application+Repository';
  addthis_pub    = '';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12" ></script>
]]></content:encoded>
			<wfw:commentRss>http://hurricanesoftwares.edublogs.org/2008/03/21/pear-php-extension-and-application-repository/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Free PHP Scripts, Source Code and Tutorial Website List</title>
		<link>http://hurricanesoftwares.edublogs.org/2008/03/11/free-php-scripts-source-code-and-tutorial-website-list/</link>
		<comments>http://hurricanesoftwares.edublogs.org/2008/03/11/free-php-scripts-source-code-and-tutorial-website-list/#comments</comments>
		<pubDate>Tue, 11 Mar 2008 09:25:35 +0000</pubDate>
		<dc:creator>Ashish</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://hurricanesoftwares.edublogs.org/2008/03/11/free-php-scripts-source-code-and-tutorial-website-list/</guid>
		<description><![CDATA[Following are the websites list who provide free php scripts. You can find lots of information about PHP as well as free code samples, code galleries, and free scripts for download at these and other sites. There may be some premium php scripts which may come for a price but overall the list is good [...]]]></description>
			<content:encoded><![CDATA[<p>Following are the websites list who provide free php scripts. You can find lots of information about PHP as well as free code samples, code galleries, and free scripts for download at these and other sites. There may be some premium php scripts which may come for a price but overall the list is good enough.</p>
<p><a href="http://www.scripts.com/php-scripts/" target="_blank">http://www.scripts.com/php-scripts/</a><br />
<a href="http://www.best-php-scripts.com/" target="_blank">http://www.best-php-scripts.com/</a><br />
<a href="http://gscripts.net/" target="_blank">http://gscripts.net/</a><br />
<a href="http://www.phpjunkyard.com/" target="_blank">http://www.phpjunkyard.com/</a><br />
<a href="http://www.free-php.net/" target="_blank">http://www.free-php.net/</a><br />
<a href="http://coding.phpground.net/" target="_blank">http://coding.phpground.net/</a><br />
<a href="http://www.atomicphp.com/" target="_blank">http://www.atomicphp.com/</a><br />
<a href="http://www.thefreecountry.com/php/index.shtml" target="_blank">http://www.thefreecountry.com/php/index.shtml</a><br />
<a href="http://www.phpbuilder.com/snippet/" target="_blank">http://www.phpbuilder.com/snippet/</a><br />
<a href="http://phpwizard.net/" target="_blank">http://phpwizard.net/</a><br />
<a href="http://www.devshed.com/Server_Side/PHP" target="_blank">http://www.devshed.com/Server_Side/PHP</a><br />
<a href="http://www.phpclasses.org/" target="_blank">http://www.phpclasses.org/</a><br />
<a href="http://px.sklar.com/" target="_blank">http://px.sklar.com/</a><br />
<a href="http://zend.com/codex.php" target="_blank">http://zend.com/codex.php</a><br />
<a href="http://www.weberdev.com/" target="_blank">http://www.weberdev.com/</a><br />
<a href="http://www.hotscripts.com/PHP/" target="_blank">http://www.hotscripts.com/PHP/</a><br />
<a href="http://www.phpresourceindex.com/" target="_blank">http://www.phpresourceindex.com/</a></p>
<p>I would be adding more to the list soon&#8230;.</p>
<script type="text/javascript">
  addthis_url    = 'http%3A%2F%2Fhurricanesoftwares.edublogs.org%2F2008%2F03%2F11%2Ffree-php-scripts-source-code-and-tutorial-website-list%2F';
  addthis_title  = 'Free+PHP+Scripts%2C+Source+Code+and+Tutorial+Website+List';
  addthis_pub    = '';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12" ></script>
]]></content:encoded>
			<wfw:commentRss>http://hurricanesoftwares.edublogs.org/2008/03/11/free-php-scripts-source-code-and-tutorial-website-list/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Parsing XML using PHP : Good example</title>
		<link>http://hurricanesoftwares.edublogs.org/2008/03/06/parsing-xml-using-php-good-example/</link>
		<comments>http://hurricanesoftwares.edublogs.org/2008/03/06/parsing-xml-using-php-good-example/#comments</comments>
		<pubDate>Thu, 06 Mar 2008 13:20:56 +0000</pubDate>
		<dc:creator>Ashish</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[XML]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://hurricanesoftwares.edublogs.org/2008/03/06/parsing-xml-using-php-good-example/</guid>
		<description><![CDATA[The following example illustrates how to use an external entity reference handler to include and parse other documents, as well as how PIs can be processed, and a way of determining &#34;trust&#34; for PIs containing code.
Consider the following XML&#8217;s
&#60; ?xml version=&#8217;1.0&#8242;?&#62;
&#60; !DOCTYPE chapter SYSTEM &#34;/just/a/test.dtd&#34; [
&#60;!ENTITY plainEntity &#34;FOO entity&#34;&#62;
&#60; !ENTITY systemEntity SYSTEM &#34;xmltest2.xml&#34;&#62;
]&#62;
&#60;chapter&#62;
&#160;&#60;title&#62;Title &#38;plainEntity;&#60;/title&#62;
&#160;&#60;para&#62;
&#160; &#60;informaltable&#62;
&#160;&#160; [...]]]></description>
			<content:encoded><![CDATA[<p>The following example illustrates how to use an external entity reference handler to include and parse other documents, as well as how PIs can be processed, and a way of determining &quot;trust&quot; for PIs containing code.</p>
<p><strong>Consider the following XML&#8217;s</strong></p>
<p>&lt; ?xml version=&#8217;1.0&#8242;?&gt;<br />
&lt; !DOCTYPE chapter SYSTEM &quot;/just/a/test.dtd&quot; [<br />
&lt;!ENTITY plainEntity &quot;FOO entity&quot;&gt;<br />
&lt; !ENTITY systemEntity SYSTEM &quot;xmltest2.xml&quot;&gt;<br />
]&gt;<br />
&lt;chapter&gt;<br />
&nbsp;&lt;title&gt;Title &amp;plainEntity;&lt;/title&gt;<br />
&nbsp;&lt;para&gt;<br />
&nbsp; &lt;informaltable&gt;<br />
&nbsp;&nbsp; &lt;tgroup cols=&quot;3&quot;&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;tbody&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;row&gt;&lt;entry&gt;a1&lt;/entry&gt;&lt;entry morerows=&quot;1&quot;&gt;b1&lt;/entry&gt;&lt;entry&gt;c1&lt;/entry&gt;&lt;/row&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;row&gt;&lt;entry&gt;a2&lt;/entry&gt;&lt;entry&gt;c2&lt;/entry&gt;&lt;/row&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp; &lt;row&gt;&lt;entry&gt;a3&lt;/entry&gt;&lt;entry&gt;b3&lt;/entry&gt;&lt;entry&gt;c3&lt;/entry&gt;&lt;/row&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;/tbody&gt;<br />
&nbsp;&nbsp; &lt;/tgroup&gt;<br />
&nbsp; &lt;/informaltable&gt;<br />
&nbsp;&lt;/para&gt;<br />
&nbsp;&amp;systemEntity;<br />
&nbsp;&lt;section id=&quot;about&quot;&gt;<br />
&nbsp; &lt;title&gt;About this Document&lt;/title&gt;<br />
&nbsp; &lt;para&gt;<br />
&nbsp;&nbsp; &lt;!&#8211; this is a comment &#8211;&gt;<br />
&nbsp;&nbsp; &lt; ?php echo &#8216;Hi!&nbsp; This is PHP version &#8216; . phpversion(); ?&gt;<br />
&nbsp; &lt;/para&gt;<br />
&nbsp;&lt;/section&gt;<br />
&lt;/chapter&gt;</p>
<p>&lt;?xml version=&quot;1.0&quot;?&gt;<br />
&lt;!DOCTYPE foo [<br />
&lt;!ENTITY testEnt &quot;test entity&quot;&gt;<br />
]&gt;<br />
&lt;foo&gt;<br />
&lt;element attrib=&quot;value&quot;/&gt;<br />
&amp;testEnt;<br />
&lt;?php echo &quot;This is some more PHP code being executed.&quot;; ?&gt;<br />
&lt;/foo&gt;</p>
<p>
<strong>The following code shows how we can parse the above XML file using PHP</strong></p>
<p>&lt; ?php<br />
$file = &quot;xmltest.xml&quot;;</p>
<p>function trustedFile($file) <br />
{<br />
&nbsp;&nbsp;&nbsp; // only trust local files owned by ourselves<br />
&nbsp;&nbsp;&nbsp; if (!eregi(&quot;^([a-z]+)://&quot;, $file) <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &amp;&amp; fileowner($file) == getmyuid()) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return true;<br />
&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp; return false;<br />
}</p>
<p>function startElement($parser, $name, $attribs) <br />
{<br />
&nbsp;&nbsp;&nbsp; echo &quot;&amp;lt;&lt;font color=\&quot;#0000cc\&quot;&gt;$name&quot;;<br />
&nbsp;&nbsp;&nbsp; if (count($attribs)) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; foreach ($attribs as $k =&gt; $v) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; echo &quot; &lt;font color=\&quot;#009900\&quot;&gt;$k&lt;/font&gt;=\&quot;&lt;font color=\&quot;#990000\&quot;&gt;$v&lt;/font&gt;\&quot;&quot;;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp; echo &quot;&amp;gt;&quot;;<br />
}</p>
<p>function endElement($parser, $name) <br />
{<br />
&nbsp;&nbsp;&nbsp; echo &quot;&amp;lt;/&lt;font color=\&quot;#0000cc\&quot;&gt;$name&lt;/font&gt;&amp;gt;&quot;;<br />
}</p>
<p>function characterData($parser, $data) <br />
{<br />
&nbsp;&nbsp;&nbsp; echo &quot;&lt;b&gt;$data&lt;/b&gt;&quot;;<br />
}</p>
<p>function PIHandler($parser, $target, $data) <br />
{<br />
&nbsp;&nbsp;&nbsp; switch (strtolower($target)) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; case &quot;php&quot;:<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; global $parser_file;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // If the parsed document is &quot;trusted&quot;, we say it is safe<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // to execute PHP code inside it.&nbsp; If not, display the code<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // instead.<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (trustedFile($parser_file[$parser])) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; eval($data);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } else {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf(&quot;Untrusted PHP code: &lt;i&gt;%s&lt;/i&gt;&quot;, <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; htmlspecialchars($data));<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; break;<br />
&nbsp;&nbsp;&nbsp; }<br />
}</p>
<p>function defaultHandler($parser, $data) <br />
{<br />
&nbsp;&nbsp;&nbsp; if (substr($data, 0, 1) == &quot;&amp;&quot; &amp;&amp; substr($data, -1, 1) == &quot;;&quot;) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf(&#8217;&lt;font color=&quot;#aa00aa&quot;&gt;%s&lt;/font&gt;&#8217;, <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; htmlspecialchars($data));<br />
&nbsp;&nbsp;&nbsp; } else {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf(&#8217;&lt;font size=&quot;-1&quot;&gt;%s&lt;/font&gt;&#8217;, <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; htmlspecialchars($data));<br />
&nbsp;&nbsp;&nbsp; }<br />
}</p>
<p>function externalEntityRefHandler($parser, $openEntityNames, $base, $systemId,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $publicId) {<br />
&nbsp;&nbsp;&nbsp; if ($systemId) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (!list($parser, $fp) = new_xml_parser($systemId)) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf(&quot;Could not open entity %s at %s\n&quot;, $openEntityNames,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $systemId);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return false;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; while ($data = fread($fp, 4096)) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (!xml_parse($parser, $data, feof($fp))) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf(&quot;XML error: %s at line %d while parsing entity %s\n&quot;,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xml_error_string(xml_get_error_code($parser)),<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xml_get_current_line_number($parser), $openEntityNames);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xml_parser_free($parser);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return false;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xml_parser_free($parser);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return true;<br />
&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp; return false;<br />
}</p>
<p>function new_xml_parser($file) <br />
{<br />
&nbsp;&nbsp;&nbsp; global $parser_file;</p>
<p>&nbsp;&nbsp;&nbsp; $xml_parser = xml_parser_create();<br />
&nbsp;&nbsp;&nbsp; xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 1);<br />
&nbsp;&nbsp;&nbsp; xml_set_element_handler($xml_parser, &quot;startElement&quot;, &quot;endElement&quot;);<br />
&nbsp;&nbsp;&nbsp; xml_set_character_data_handler($xml_parser, &quot;characterData&quot;);<br />
&nbsp;&nbsp;&nbsp; xml_set_processing_instruction_handler($xml_parser, &quot;PIHandler&quot;);<br />
&nbsp;&nbsp;&nbsp; xml_set_default_handler($xml_parser, &quot;defaultHandler&quot;);<br />
&nbsp;&nbsp;&nbsp; xml_set_external_entity_ref_handler($xml_parser, &quot;externalEntityRefHandler&quot;);<br />
&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp; if (!($fp = @fopen($file, &quot;r&quot;))) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return false;<br />
&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp; if (!is_array($parser_file)) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; settype($parser_file, &quot;array&quot;);<br />
&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp; $parser_file[$xml_parser] = $file;<br />
&nbsp;&nbsp;&nbsp; return array($xml_parser, $fp);<br />
}</p>
<p>if (!(list($xml_parser, $fp) = new_xml_parser($file))) {<br />
&nbsp;&nbsp;&nbsp; die(&quot;could not open XML input&quot;);<br />
}</p>
<p>echo &quot;&lt;pre&gt;&quot;;<br />
while ($data = fread($fp, 4096)) {<br />
&nbsp;&nbsp;&nbsp; if (!xml_parse($xml_parser, $data, feof($fp))) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; die(sprintf(&quot;XML error: %s at line %d\n&quot;,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xml_error_string(xml_get_error_code($xml_parser)),<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xml_get_current_line_number($xml_parser)));<br />
&nbsp;&nbsp;&nbsp; }<br />
}<br />
echo &quot;&lt;/pre&gt;&quot;;<br />
echo &quot;parse complete\n&quot;;<br />
xml_parser_free($xml_parser);</p>
<p>?&gt;</p>
<p>I hope this will help. Your comments are welcome.</p>
<script type="text/javascript">
  addthis_url    = 'http%3A%2F%2Fhurricanesoftwares.edublogs.org%2F2008%2F03%2F06%2Fparsing-xml-using-php-good-example%2F';
  addthis_title  = 'Parsing+XML+using+PHP+%3A+Good+example';
  addthis_pub    = '';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12" ></script>
]]></content:encoded>
			<wfw:commentRss>http://hurricanesoftwares.edublogs.org/2008/03/06/parsing-xml-using-php-good-example/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
