<?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>Blog - Alex-Elliott.co.uk &#187; php</title>
	<atom:link href="http://alex-elliott.co.uk/blog/category/php/feed" rel="self" type="application/rss+xml" />
	<link>http://alex-elliott.co.uk/blog</link>
	<description>The internet home of a prospective software engineer</description>
	<lastBuildDate>Thu, 29 Jul 2010 18:00:24 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
<image>
			<title>Blog - Alex-Elliott.co.uk</title>
			<url>http://alex-elliott.co.uk/favicon.png</url>
			<link>http://alex-elliott.co.uk/blog</link>
			<width>16</width>
			<height>16</height>
			<description>The internet home of a prospective software engineer</description>
		</image>		<item>
		<title>My Little FAQ For PHP Pitfalls</title>
		<link>http://alex-elliott.co.uk/blog/2009/11/php/my-little-faq-for-php-pitfalls</link>
		<comments>http://alex-elliott.co.uk/blog/2009/11/php/my-little-faq-for-php-pitfalls#comments</comments>
		<pubDate>Fri, 06 Nov 2009 22:54:47 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://alex-elliott.co.uk/blog/?p=62</guid>
		<description><![CDATA[There are a few questions which come up time and time again in Zymic&#8217;s support channels (Zymic IRC, or the forums) and having answered them several times, I feel I would like to spend some time writing up a response which I hope can make handling these support queries a bit easier. So, ok, firstly: [...]]]></description>
			<content:encoded><![CDATA[<p>There are a few questions which come up time and time again in Zymic&#8217;s support channels (Zymic IRC, or the forums) and having answered them several times, I feel I would like to spend some time writing up a response which I hope can make handling these support queries a bit easier.  So, ok, firstly:</p>
<h2>PHP Notices</h2>
<p>Since Zymic&#8217;s PHP is set to display errors of the level E_NOTICE, users often find they are getting errors on Zymic that they are not getting on their local test server or previous host.  E_NOTICE level errors are good practice recommendations that point out where you&#8217;ve written valid but improper PHP.  It is recommended that rather than suppress E_NOTICE level warnings you display them during the development process and fix your code so that the errors are never generated.  This improves the quality and reliability of your code.</p>
<p>If your local test server does not display notices then I would recommend you change your local PHP configuration to start generating them.  You can do this by modifying the &#8220;error_reporting&#8221; directive in your php.ini file.  In a system where notices are disabled it is typically set up as this:</p>
<p><code>error_reporting = E_ALL &amp; ~E_NOTICE</code></p>
<p>This format takes E_ALL, a group of many error levels including notices, and then removes notices from the list by adding ~E_NOTICE (not E_NOTICE).  So you can enable E_NOTICE level errors by making it simply:</p>
<p><code>error_reporting = E_ALL</code></p>
<p>The next few topics are about some specific E_NOTICE level errors you may have found and what they mean then how to resolve them.</p>
<h2>PHP Notice: Undefined Index or Undefined Variable</h2>
<p>This notice refers to using a variable or a member of an array that has not been defined prior to its use.  The simplest example of this is to take this code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
   <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$foo</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// At no point have we defined $foo, so using it is probably bad</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>This will produce an error along the lines of &#8220;PHP Notice:  Undefined variable: foo in __FILE__ on __LINE__&#8221;.  This is obviously a very trivial example and it rarely comes that simple in real code, but it is an illustration of what triggers this error.  Attempting to reference some data that doesn&#8217;t exist can easily lead to unexpected behaviour, and it&#8217;s fairly obvious that all variables/array members you try to read from should be defined and initialised before you try that read.</p>
<p>A common context where &#8220;Undefined Index&#8221; will turn up is in people handling the superglobals like $_POST.  If you attempt to use $_POST['foo'] without checking some input with the name &#8220;foo&#8221; has been posted to the script will trigger this notice.  So, that&#8217;s what the notice is and what causes it, but how can you prevent it from appearing?  Well, there are some tests that PHP has which can check the data, and then you can make sure that you&#8217;re only attempting to read the data if the variable/array member is set or is not empty.  So say you want something that outputs &#8220;Hello, {name}&#8221; to the browser and it works on GET data, an implementation which will trigger this notice might be:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
   <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'Hello, '</span><span style="color: #339933;">,</span> <span style="color: #990000;">htmlspecialchars</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'name'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">ENT_QUOTES</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>But this script doesn&#8217;t work particularly well when a name isn&#8217;t provided, you will get a notice and the output will just be &#8220;Hello, &#8220;, which is not particularly meaningful &#8211; we can do better than that.  So if we add in a check using PHP&#8217;s <a href="http://www.php.net/empty">empty</a>() function to see if there is some data provided we could instead write:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
   <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'Hello, '</span><span style="color: #339933;">;</span>
   <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">empty</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'name'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
      <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'Stranger'</span><span style="color: #339933;">;</span>
   <span style="color: #b1b100;">else</span>
      <span style="color: #b1b100;">echo</span> <span style="color: #990000;">htmlspecialchars</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'name'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">ENT_QUOTES</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>This is very similar to the last, but it will not trigger a notice if there is no name provided to the script, and in fact handles it by instead outputting &#8220;Hello, Stranger&#8221; if no name is provided.  This is a bit more elegant, and there are many ways you could tackle this.  You could have the case where if no input is provided we show a form instead for the user to provide a name.</p>
<h2>PHP Notice: Use of undefined constant</h2>
<p>This one is very much similar to the last one, but is worth mentioning separately because there&#8217;s enough to be said about the mistakes that lead to it, and how you can make these mistakes and not realise it without the benefit of notices.  This notice is about the use of undefined constants in code, the interesting thing is how PHP handles a case where an undefined constant is found.  It will trigger this notice, but since this is valid PHP it will take a value for the constant for the script to use, and that is the identifier (or name) of the constant, thus an undefined constant foo will evaluate to the string &#8216;foo&#8217;.</p>
<p>Because of this fact you often see cases where an array member is referenced via $array[foo] rather than $array['foo'].  If notices are disabled, then it is possible that the author of that code will not notice the mistake (though syntax highlighting in your editor should mitigate this somewhat) because while foo is an undefined constant the two are equivalent.  <strong>However</strong>, this is not always the case.  An easy example to demonstrate this is this.  Take file1.php to be this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
   <span style="color: #000088;">$array</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'foo'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'Hello there'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'bar'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'Goodbye'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$array</span><span style="color: #009900;">&#91;</span>foo<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// Note here we've not quoted foo so it's a constant,</span>
                     <span style="color: #666666; font-style: italic;">// and in the context of just this script it's undefined.</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>When you visit this page you will find it triggers this notice and outputs &#8220;Hello there&#8221;, however if we were to also have a file2.php containing this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
   <span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'foo'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'bar'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// define the constant foo with the value &quot;bar&quot;</span>
   <span style="color: #b1b100;">require</span> <span style="color: #0000ff;">'file1.php'</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// and then bring in the file we just wrote,</span>
                        <span style="color: #666666; font-style: italic;">// with this constant in scope</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>When you visit file2.php you&#8217;ll find the notice has gone and we&#8217;re now presented with &#8220;Goodbye&#8221;, this is the crux of the issue, when you unintentionally use an undefined constant you no longer have any idea how that script will run when it is part of a larger program.  What it will actually do is now undefined behaviour.  So, if what you mean to write is a string, make sure it has quotes around it, so the PHP parser knows that it&#8217;s a string &#8211; not a constant.</p>
<h2>That&#8217;s it&#8230; for now</h2>
<p>I may add to this at a later date to add in anything else that gets asked frequently, we shall see.</p>
]]></content:encoded>
			<wfw:commentRss>http://alex-elliott.co.uk/blog/2009/11/php/my-little-faq-for-php-pitfalls/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Arbutus TC v1</title>
		<link>http://alex-elliott.co.uk/blog/2009/01/php/arbutus-tc-v1</link>
		<comments>http://alex-elliott.co.uk/blog/2009/01/php/arbutus-tc-v1#comments</comments>
		<pubDate>Wed, 07 Jan 2009 21:39:24 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[arbutus]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://alex-elliott.co.uk/blog/?p=52</guid>
		<description><![CDATA[So, what have I been doing with my time recently? Bits and pieces of personal project tinkering, and also one small paid project. This project was a website for the Systems Engineering consulting company Arbutus Technical Consulting. It was recognised that they needed an effective web presence to help bring in business for the company, [...]]]></description>
			<content:encoded><![CDATA[<p>So, what have I been doing with my time recently?  Bits and pieces of personal project tinkering, and also one small paid project.  This project was a website for the Systems Engineering consulting company Arbutus Technical Consulting.  It was recognised that they needed an effective web presence to help bring in business for the company, and I was hired to build that website to the specification provided.</p>
<p>The website was specified to be a very simple, mostly static collection of pages including an easy to use blog system for comments the company&#8217;s primary consultant had on issues related to Systems Engineering.  I designed a simple interface and translated that into a working website which Arbutus can use to advertise themselves to potential clients.</p>
<p>If you&#8217;re interested then have a look at what I came up with for <a title="Visit Arbutus Technical Consulting" href="http://arbutus-tc.co.uk/">Arbutus Technical Consulting</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://alex-elliott.co.uk/blog/2009/01/php/arbutus-tc-v1/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>zBot No More</title>
		<link>http://alex-elliott.co.uk/blog/2008/12/php/zbot-no-more</link>
		<comments>http://alex-elliott.co.uk/blog/2008/12/php/zbot-no-more#comments</comments>
		<pubDate>Sat, 13 Dec 2008 16:44:39 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[polymer]]></category>
		<category><![CDATA[projects]]></category>

		<guid isPermaLink="false">http://alex-elliott.co.uk/blog/?p=43</guid>
		<description><![CDATA[The title here is more sensational than it needs to be, I&#8217;m not discontinuing the zbot 2.0 project &#8211; rather, I&#8217;ve just decided that if I want to release it publicly, then I would like a more generic parent name for the software.  The instance of the bot in irc.zymic.com will likely retain the name. [...]]]></description>
			<content:encoded><![CDATA[<p>The title here is more sensational than it needs to be, I&#8217;m not discontinuing the zbot 2.0 project &#8211; rather, I&#8217;ve just decided that if I want to release it publicly, then I would like a more generic parent name for the software.  The instance of the bot in irc.zymic.com will likely retain the name. <img src='http://alex-elliott.co.uk/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>So, what&#8217;s the new name for the software?  Well, that&#8217;s possibly still in flux, but for the moment I&#8217;ve decided I might go with <strong>polymer</strong>.  A slightly nerdy nod to the fact I want to make this release inherently extensible, as much as is needed.</p>
<h2>Polymerisation</h2>
<p>Of course, with a name like that I really should elaborate on just why it&#8217;s going to be more modular and easily extensible than the previous bot.</p>
<p>There was nothing really wrong with the implementation before, and much of it has been kept constant in the new implementation.  The most notable changes are in the format used to write modules, which has been simplified somewhat &#8211; and the fact that module interaction will be made possible allowing modules to reuse functionality included in a module that is already loaded into the bot.</p>
<p>My current <acronym title="Work in Progress">WIP</acronym> draft for module layout is this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// module description up here?</span>
<span style="color: #666666; font-style: italic;">//</span>
<span style="color: #666666; font-style: italic;">// that would make sense.</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> mod_example
<span style="color: #009900;">&#123;</span>
   <span style="color: #666666; font-style: italic;">// any local variables required</span>
   <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$localvar</span><span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$othervar</span><span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #666666; font-style: italic;">/// Core and required methods:</span>
   <span style="color: #666666; font-style: italic;">// init, performs any initialisation required</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> init<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;">// initialisation stuff... for example:</span>
      <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">loadConfig</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;">// &lt;-- (re)loads configuration in {confdir}/{name}.conf</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// the triggers and hooks</span>
      registerTrigger<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'ping'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'respond'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      registerHook<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'passive'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #666666; font-style: italic;">// a rehash method which handles a complete config reload</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> rehash<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;">// rejig internals in case our config has changed</span>
      <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">loadConfig</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;">// &lt;-- like this again perhaps?</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #666666; font-style: italic;">/// about() and help() will probably make an appearance though since some are</span>
   <span style="color: #666666; font-style: italic;">/// internal they need not include them.</span>
&nbsp;
   <span style="color: #666666; font-style: italic;">/// Trigger/Hook implementation</span>
   <span style="color: #666666; font-style: italic;">// Here's a trigger, triggered of course by a !ping command.</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> respond<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;">// note the lack of any arguments, instead the information will automatically</span>
      <span style="color: #666666; font-style: italic;">// be made available through methods/variables contained within the base</span>
      <span style="color: #666666; font-style: italic;">// class.  This simplifies format, and allows us to make triggers and hooks</span>
      <span style="color: #666666; font-style: italic;">// constant.</span>
      <span style="color: #000088;">$target</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">state</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">target</span><span style="color: #339933;">;</span>
      <span style="color: #000088;">$nick</span>   <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">state</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">caller</span><span style="color: #339933;">;</span>
      <span style="color: #666666; font-style: italic;">// module intercommunication:</span>
      <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> <span style="color: #990000;">is_object</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_irc</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span>
         <span style="color: #000088;">$_irc</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">msg</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$target</span><span style="color: #339933;">,</span><span style="color: #000088;">$nick</span><span style="color: #339933;">.</span><span style="color: #0000ff;">', pong'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #666666; font-style: italic;">// And here's a hook, called on every new packet</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> passive<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;">// do stuff</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #666666; font-style: italic;">/// And as always, you can declare internal functions for personal use.</span>
   <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">function</span> helper<span style="color: #009900;">&#40;</span><span style="color: #000088;">$arg1</span><span style="color: #339933;">,</span><span style="color: #000088;">$arg2</span><span style="color: #009900;">&#41;</span>
   <span style="color: #009900;">&#123;</span>
      <span style="color: #666666; font-style: italic;">// do something helpful</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>This format may undergo changes as I work on it, but it&#8217;s likely to look something like the above when I&#8217;m done. <img src='http://alex-elliott.co.uk/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Any suggestions/comments are very welcome, since this is going to be the interface anyone who wants to write modules will be using, so it&#8217;s important that it&#8217;s suitably intuitive.</p>
]]></content:encoded>
			<wfw:commentRss>http://alex-elliott.co.uk/blog/2008/12/php/zbot-no-more/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Concurrency in PHP</title>
		<link>http://alex-elliott.co.uk/blog/2008/11/php/concurrency-in-php</link>
		<comments>http://alex-elliott.co.uk/blog/2008/11/php/concurrency-in-php#comments</comments>
		<pubDate>Thu, 13 Nov 2008 20:28:51 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[zbot]]></category>
		<category><![CDATA[concepts]]></category>
		<category><![CDATA[concurrency]]></category>

		<guid isPermaLink="false">http://alex-elliott.me/?p=14</guid>
		<description><![CDATA[One of the problems you come across when writing real-time applications in PHP is that it is in most cases a linear language, performing the tasks set before it one at a time and doesn&#8217;t contain much in the way of tools to help set up concurrent tracks of evaluation. As far as I&#8217;m aware [...]]]></description>
			<content:encoded><![CDATA[<p>One of the problems you come across when writing real-time applications in PHP is that it is in most cases a linear language, performing the tasks set before it one at a time and doesn&#8217;t contain much in the way of tools to help set up concurrent tracks of evaluation.</p>
<p>As far as I&#8217;m aware PHP doesn&#8217;t contain anything at all for controlling threads, however it does include some process control functions which allows us to use a multi-process model for concurrent programming.</p>
<h2>Introducing Process Control</h2>
<p>The functions we need come via the <a title="Documentation on the Process Control module" href="http://www.php.net/manual/en/book.pcntl.php">Process Control module</a> in PHP.  This is not included by default in the PHP Apache module (because it&#8217;s more complicated in such cases), if you want to use it for a website you will need to use PHP as a CGI module or compile mod_php with <span class="option"><em>&#8211;enable-pcntl</em>, in this case I&#8217;ll be testing using the PHP CLI binary, in which it&#8217;s included by default.</span></p>
<p>The key function that this module provides for us is <strong>pcntl_fork()</strong>.  This works much like the fork you may have come across in other languages, it creates a clone of the current process which then computes a separate code path to the parent that called it.  The important thing of course being that the clone (or child) process does its computation while the parent carries on with whatever it was doing.  This is key to parallelising our PHP applications, and allows us to create responsive applications which can still do lengthy tasks.</p>
<h2>Process Control in Use</h2>
<p>So where might this be useful?  A trivial example would be when you want to perform a task that takes a number of seconds, and you want the user to receive output from the program while it&#8217;s being computed.  A simple example of this could be the code below:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// this is a place-holder for a hypothetical function</span>
<span style="color: #666666; font-style: italic;">// which takes a long time to compute, let's say the</span>
<span style="color: #666666; font-style: italic;">// eventual answer would be 5...</span>
<span style="color: #000000; font-weight: bold;">function</span> foo<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
   <span style="color: #990000;">sleep</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">10</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #b1b100;">return</span> <span style="color: #cc66cc;">5</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #990000;">file_put_contents</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'tmp'</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// we'll also assume we know the answer isn't 0.</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Here's the fork, the process ID will be stored in $pid for the main</span>
<span style="color: #666666; font-style: italic;">// program, and it'll be 0 for the child process.</span>
<span style="color: #000088;">$pid</span> <span style="color: #339933;">=</span> pcntl_fork<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: #000088;">$pid</span> <span style="color: #339933;">==</span> <span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span>
   <span style="color: #990000;">die</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Fork failed'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// Our fork failed, thus our program did.</span>
<span style="color: #b1b100;">elseif</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$pid</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: #666666; font-style: italic;">// here's our forked process</span>
   <span style="color: #990000;">file_put_contents</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'tmp'</span><span style="color: #339933;">,</span>foo<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: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Done<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
   <span style="color: #990000;">exit</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// In the meantime we'll keep our parent process looping.</span>
<span style="color: #000088;">$timestamp</span> <span style="color: #339933;">=</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: #b1b100;">while</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">file_get_contents</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'tmp'</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: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$timestamp</span> <span style="color: #339933;">!=</span> <span style="color: #990000;">time</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>    <span style="color: #666666; font-style: italic;">// once a second...</span>
      <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'Calculating...'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// give some output</span>
   <span style="color: #000088;">$timestamp</span> <span style="color: #339933;">=</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: #009900;">&#125;</span>
&nbsp;
<span style="color: #b1b100;">echo</span> <span style="color: #990000;">file_get_contents</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'tmp'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// output our answer from the fork.</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>As you see we have simply made a test-case here, there&#8217;s a function with a <em>sleep(10);</em> which takes the place of any long-running function, and while it is running we inform the user that the task is underway, once a second until it is complete.  It&#8217;s quite a trivial example, but it shows that both the echo statements and the sleep were functioning in parallel when viewing the output, which is predictably as follows:</p>
<pre>bash-3.1$ php -f test.php
Calculating...
Calculating...
Calculating...
Calculating...
Calculating...
Calculating...
Calculating...
Calculating...
Calculating...
Done
5</pre>
<p>Another example might be if you were performing a repetitive task on many targets, such as all the files in a directory.  You could loop across the directory forking off a new process which would handle each file, then back in the main loop you simply wait for all of the processes to finish and then wrap up any loose ends you might have.</p>
<h2>Conclusion</h2>
<p>So there you go, process control.  A useful tool if you need to speed up a parallelisable program/algorithm.  Of course, in most cases speed isn&#8217;t too necessary in PHP applications, so the practical applications of process control aren&#8217;t very numerous.  In cases where speed is not important, it is usually better to keep the application simple, since it means it is more likely to be correct.</p>
<p>However, if you are writing something real-time, but don&#8217;t want to bog down your main application loop &#8211; making your application unresponsive, process control comes into its own and will save the day.</p>
<h2>Concurrency in zBot</h2>
<p>As I mentioned in the previous post, concurrency is something I&#8217;ve been meaning to include in zbot for a while now.  zbot is a real-time PHP application, and as an IRC bot, a response time of over a second or two is starting to seem sluggish.  Sometimes however some responses can&#8217;t be given in this length of time because they rely on an external site, and so the bot must wait for a response before it can reply.  In such cases I would like the main loop to be free to continue watching for more easily serviced queries.  So that it could reply to those first while it is waiting.</p>
<p>It also allows me to safely parcel off largish tasks without having to worry that the bot will ping out, as the core will continue looking for PING packets.  For example, I would like to implement a news plugin which would download five or more RSS feeds and then parse them to check for new news stories.  This would be ideal for process control, as I could fork off another process which would handle the downloads and parsing while the main bot continues to function.</p>
<p>For this purpose I have written a <em>taskScheduler</em> class to which I can send jobs which are then evaluated in a forked process.  The class keeps track of all scheduled jobs, and performs a callback when the job is completed.  This might prove to be a useful separate class, so I&#8217;ll likely both include it in zbot, and separately on my site with some documentation when it&#8217;s finished.</p>
]]></content:encoded>
			<wfw:commentRss>http://alex-elliott.co.uk/blog/2008/11/php/concurrency-in-php/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A New zBot</title>
		<link>http://alex-elliott.co.uk/blog/2008/11/php/a-new-zbot</link>
		<comments>http://alex-elliott.co.uk/blog/2008/11/php/a-new-zbot#comments</comments>
		<pubDate>Thu, 13 Nov 2008 15:17:30 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[zbot]]></category>
		<category><![CDATA[bot]]></category>
		<category><![CDATA[plan]]></category>

		<guid isPermaLink="false">http://alex-elliott.me/?p=11</guid>
		<description><![CDATA[I did say there was news of a project coming up, so here it is.  Version 2.0 of my PHP IRC bot, zbot (on irc.zymic.com).  It&#8217;s been out of action for a while, since it was hosted on a machine I don&#8217;t have access to at the moment (no SSH, bleh).  But there&#8217;s a (better) [...]]]></description>
			<content:encoded><![CDATA[<p>I did say there was news of a project coming up, so here it is.  Version 2.0 of my PHP IRC bot, zbot (on irc.zymic.com).  It&#8217;s been out of action for a while, since it was hosted on a machine I don&#8217;t have access to at the moment (no SSH, bleh).  But there&#8217;s a (better) alternative now, so I can start work on getting it back.</p>
<h2>Identifying the problem(s)</h2>
<p>Building a new 2.0 version of my IRC bot has been something I&#8217;ve wanted to do for a while now, and there are a few main reasons why I&#8217;ve decided that it should be a fresh start rather than an update.  These are mostly (fairly) fundamental feature issues, which should be implemented quite a long way down the source tree &#8211; and so modifying the source to patch them in would be a tedious and lengthy process which might introduce a fair few bugs into the codebase.</p>
<p>The main things I want to improve in the new version are as follows:</p>
<ul>
<li>Generally cleaner code (I might choose to release this source publicly, and I want it to be nice).</li>
<li>Improve the module system to allow the modules to intercommunicate, by doing this I can abstract even some of the &#8220;core&#8221; functionality into modules, which will allow for patches at a later date without a restart.</li>
<li>Ground-up design for a bot rehash feature, in which it reloads all settings from configuration files.</li>
<li>Simpler text-file configuration files which will be parsed and read-in.</li>
<li>Work out a system for concurrency, perhaps spawning child PHP processes to handle any tasks which might take a long time (such as fetching files online), this would free up the rest of the core loop to handle other input while these tasks are performed.</li>
<li>Additional bot features, such as automatic tracking of users in channels, dynamic topic changes (so for example, we could specify a field which would be changed by an external source, allowing us to do things like include the current stable version number of PHP in #php).</li>
<li>Web interfaces for some bot data, like current factoids, quotes, and possibly a module repository that people could submit to.</li>
</ul>
<h2>Moving forward</h2>
<p>I hope to look at building a new version soon, sorting some groundwork for things at the moment, I&#8217;ll try to keep this updated as work goes on.</p>
<p>Of course, my good buddy Ed (Bread) will probably assist as he did in the last version (he provided the initial module system and a few plugins), and maybe this time we&#8217;ll actually write some documentation so people can write their own modules easily! :p</p>
<p>Since I will be hosting this on my shiny new VPS, we have more freedom (having a web interface was not possible before), and it means we can have one central source tree (I&#8217;m thinking stable/ and testing/ with a script to update stable when testing is shown not to break things <img src='http://alex-elliott.co.uk/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ).</p>
]]></content:encoded>
			<wfw:commentRss>http://alex-elliott.co.uk/blog/2008/11/php/a-new-zbot/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
