<?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>Fishtrap</title>
	<atom:link href="http://fishtrap.co.uk/feed/" rel="self" type="application/rss+xml" />
	<link>http://fishtrap.co.uk</link>
	<description>php and other stuff I know</description>
	<lastBuildDate>Tue, 24 Apr 2012 15:46:19 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4-alpha-19931</generator>
		<item>
		<title>Multiple PHP versions from git</title>
		<link>http://fishtrap.co.uk/blog/2012/04/20/multiple-php-versions-from-git/</link>
		<comments>http://fishtrap.co.uk/blog/2012/04/20/multiple-php-versions-from-git/#comments</comments>
		<pubDate>Fri, 20 Apr 2012 13:26:23 +0000</pubDate>
		<dc:creator>nat</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://fishtrap.co.uk/?p=925</guid>
		<description><![CDATA[A while back I read Derick Rethans post on how he compiles multiple versions of PHP which he posted back in November 2011. Of the many possible solutions out there this one seemed the most flexible, however, the php project &#8230; <a href="http://fishtrap.co.uk/blog/2012/04/20/multiple-php-versions-from-git/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>A while back I read <a href="http://derickrethans.nl/multiple-php-version-setup.html" target="_blank" onclick="pageTracker._trackPageview('/outgoing/derickrethans.nl/multiple-php-version-setup.html?referer=');">Derick Rethans post on how he compiles multiple versions of PHP</a> which he posted back in November 2011. Of the many possible solutions out there this one seemed the most flexible, however, the php project has now moved to git as it its source code management tool so it requires a few changes. Git means it is now faster and a bit simpler to pull down different branches and build from them. Git also has the added benefit that it is possible to do so from <a href="https://github.com/natmchugh/php-src" target="_blank" onclick="pageTracker._trackPageview('/outgoing/github.com/natmchugh/php-src?referer=');">your own fork of the PHP repo</a>.</p>
<p>Here is my version of Derick&#8217;s bash script. It is tuned for building on a mac or BSD. You many need to fiddle around with the compile flags to get it work on your system. There are also some hard coded paths which will need altering.</p>
<pre class="brush: bash; title: ;">
#!/bin/sh

VERSION=$1
DEBUG=$2
ZTS=$3
THIRTYTWO=$4
POSTFIX=
EXTRA_FLAGS=

if (test &quot;${DEBUG}&quot; = &quot;nodebug&quot;); then
	POSTFIX=&quot;$POSTFIX-nodebug&quot;
else
	EXTRA_FLAGS=&quot;$EXTRA_FLAGS --enable-debug&quot;
fi

if (test &quot;${ZTS}&quot; = &quot;zts&quot;); then
	EXTRA_FLAGS=&quot;$EXTRA_FLAGS --enable-maintainer-zts&quot;
	POSTFIX=&quot;$POSTFIX-zts&quot;
fi

if (test &quot;${THIRTYTWO}&quot; = &quot;32bit&quot;); then
	export CFLAGS=&quot;-m32&quot;
	POSTFIX=&quot;$POSTFIX-32bit&quot;
fi

PHP_DIR=/Users/nathanielmchugh/nmdev/php/php-src/
cd $PHP_DIR

SCRUBBED=`echo $VERSION | sed 's/[0-9.]*//'`
if (test &quot;${SCRUBBED}&quot; = &quot;dev&quot;); then
	BRANCH=`echo PHP-${VERSION} | sed 's/dev//'`
	git checkout $BRANCH
else
	TAG=`echo php-${VERSION} `
	git checkout $TAG
fi

echo &quot;Building ${VERSION}${POSTFIX} with ($EXTRA_FLAGS)&quot;

make clean
rm -rf configure
./vcsclean
./buildconf --force

if (test &quot;${THIRTYTWO}&quot; = &quot;32bit&quot;); then
	OPTIONS=&quot;--disable-all&quot;
else
	OPTIONS=&quot;--with-gd --with-jpeg-dir=/opt/local --with-png-dir=/opt/local --with-xpm-dir=/opt/local --with-freetype-dir=/opt/local \
		--with-mysql=mysqlnd --enable-bcmath --with-gmp=/opt/local --with-readline=/opt/local \
		--with-openssl --with-curl --without-esmtp \
		--with-mysqli=mysqlnd --enable-pcntl \
		--enable-memory-limit --with-mcrypt=/opt/local \
		--with-iconv=/opt/local --enable-wddx  \
		--enable-spl --enable-pdo --with-pdo-mysql --with-pdo-sqlite \
		--with-ctype --with-bz2 --enable-mbstring --with-mime-magic \
		--with-xmlrpc --with-zlib --disable-zend-memory-manager --with-esmtp \
		--with-xsl --enable-exif --enable-soap --enable-ftp&quot;
fi

./configure \
--prefix=/usr/local/php/${VERSION}${POSTFIX} ${EXTRA_FLAGS} ${OPTIONS}

make -j 5
make install
</pre>
<p>Heres an example of using it to build the stable version of php5.4</p>
<pre class="brush: bash; title: ;">
$sudo ./php-build.sh 5.4.0
$pe 5.4.0
$php - v
PHP 5.4.0 (cli) (built: Apr 20 2012 12:37:52) (DEBUG)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies
</pre>
]]></content:encoded>
			<wfw:commentRss>http://fishtrap.co.uk/blog/2012/04/20/multiple-php-versions-from-git/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mysqlnd_uh presentation</title>
		<link>http://fishtrap.co.uk/blog/2012/02/13/mysqlnd_uh-presentation/</link>
		<comments>http://fishtrap.co.uk/blog/2012/02/13/mysqlnd_uh-presentation/#comments</comments>
		<pubDate>Mon, 13 Feb 2012 16:00:19 +0000</pubDate>
		<dc:creator>nat</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[mysqlnd]]></category>

		<guid isPermaLink="false">http://fishtrap.co.uk/?p=900</guid>
		<description><![CDATA[I gave a short talk on mysqlnd_uh and the whole mysqlnd extension as SheffPHP. Not sure how interesting people found it. I think many people switch off when databases are mentioned. Here are some slides any way. Mysqlnd uh]]></description>
			<content:encoded><![CDATA[<p>I gave a short talk on mysqlnd_uh and the whole mysqlnd extension as SheffPHP. Not sure how interesting people found it. I think many people switch off when databases are mentioned. Here are some slides any way.</p>
<div style="width:425px" id="__ss_11536367"><strong style="display:block;margin:12px 0 4px"><a href="http://www.slideshare.net/natmchugh/mysqlnd-uh" title="Mysqlnd uh" onclick="pageTracker._trackPageview('/outgoing/www.slideshare.net/natmchugh/mysqlnd-uh?referer=');">Mysqlnd uh</a></strong><object id="__sse11536367" width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=mysqlnduh-120212101347-phpapp01&#038;stripped_title=mysqlnd-uh&#038;userName=natmchugh" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><param name="wmode" value="transparent"/><embed name="__sse11536367" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=mysqlnduh-120212101347-phpapp01&#038;stripped_title=mysqlnd-uh&#038;userName=natmchugh" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="transparent" width="425" height="355"></embed></object></div>
]]></content:encoded>
			<wfw:commentRss>http://fishtrap.co.uk/blog/2012/02/13/mysqlnd_uh-presentation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mysqlnd_qc Query caching in the client</title>
		<link>http://fishtrap.co.uk/blog/2011/11/22/mysqlnd_qc-query-caching-in-the-client/</link>
		<comments>http://fishtrap.co.uk/blog/2011/11/22/mysqlnd_qc-query-caching-in-the-client/#comments</comments>
		<pubDate>Tue, 22 Nov 2011 17:16:38 +0000</pubDate>
		<dc:creator>nat</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[mysqlnd]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://fishtrap.co.uk/?p=857</guid>
		<description><![CDATA[One of the uses for mysqlnd&#8217;s plugin architecture that I found most interesting was query caching on the client. The traditional MySQL Query Cache The MySQL query cache is a really nice simple feature which helps speed up repeated queries &#8230; <a href="http://fishtrap.co.uk/blog/2011/11/22/mysqlnd_qc-query-caching-in-the-client/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>One of the uses for mysqlnd&#8217;s plugin architecture that I found most interesting was query caching on the client.</p>
<h3>The traditional MySQL Query Cache</h3>
<p>The MySQL query cache is a really nice simple feature which helps speed up repeated queries of the same data. A certain portion of memory can be set aside to hold results sets in a look table against the query string. When a SELECT query comes in which the MySQL server has seen before it looks in the query cache and if it has seen the query before it doesn&#8217;t touch the table data or indexes instead it simply returns the result set it has in memory which is much faster.  This is particularly useful in web applications where repeated SELECT queries are very common.</p>
<p>Here&#8217;s a little script to demo the effect query cache can have</p>
<pre class="brush: php; title: ;">
&lt;?php
$mysqli = new mysqli('127.0.0.1', 'root', '', 'war_and_peace');
$mysqli-&gt;query('RESET QUERY CACHE');
$querySQL = &quot;SELECT * FROM words WHERE word = 'sausage' &quot;;
$time_start = microtime(true);
if ($results = $mysqli-&gt;query($querySQL)) {
 echo &quot;Cold got {$results-&gt;num_rows} results in &quot;;
 echo microtime(true) - $time_start,&quot;s&quot;,PHP_EOL;
 $results-&gt;close();
}
$time_start = microtime(true);
if ($results = $mysqli-&gt;query($querySQL)) {
 echo &quot;Server cache got {$results-&gt;num_rows} results in &quot;;
 echo microtime(true) - $time_start,&quot;s&quot;,PHP_EOL;
 $results-&gt;close();
}
</pre>
<p>Running this script against a completely un-normalised table with the 600 thousand odd words of war and peace (thanks <a href="http://www.gutenberg.org/" onclick="pageTracker._trackPageview('/outgoing/www.gutenberg.org/?referer=');">Project Gutenberg</a>) in it gives you</p>
<pre class="brush: bash; title: ;">
$ php MySQL_QueryCache.php
Cold got 5 results in 0.13019204139709s
Server cache got 5 results in 0.00035595893859863s
</pre>
<h3>Why not put this in the client?</h3>
<p>What would make it even faster is if the client did not need to connect to the server at all. If the client had a cache of all queries it performed it could save the time taken for the network round trip and help take load off the server by not even asking the question.</p>
<p><a href="http://pecl.php.net/package/mysqlnd_qc" onclick="pageTracker._trackPageview('/outgoing/pecl.php.net/package/mysqlnd_qc?referer=');">mysqlnd_qc </a> attempts to do this.</p>
<p>There is, however, a major problem though, cache invalidation. In the traditional server based cache a very simple table based cache invalidation algorithm is used. If a query which alters the data in a table is detected all caches of data with that table in the result set are invalidated. This will even work for servers which are part of a replication cluster since the update sql will propagate from the master where the data was updated to the slaves and the slaves&#8217; caches will then be invalidated.</p>
<p>But what if there are multiple clients? One client could update a table while another client still thinks its cache is still valid and so continues to serve it. The situation of two clients is actually relevant even if you don&#8217;t have multiple web servers talking to the same database server. It could occur by using something other than PHP and mysqlnd to connect the database. For instance using the command line mysql client (which uses libmysql) any updates made through this would not invalidate other clients query caches.</p>
<p>This problem is seemingly insoluble without some complex mechanism of feeding back to every client which caches are still valid. So the simple answer is to only cache for a few seconds and then only use the caching where slightly stale data is not hugely important.</p>
<p>Therefore by default after installing the extension with a quick</p>
<pre class="brush: bash; title: ;">
phpize
./configure
make
sudo make install
</pre>
<p>(you will need to be using mysqlnd obviously to be able to use it)</p>
<p>You will need to prefix all queries you want to cache with </p>
<p>&#8220;/*qc=on*/ SELECT * from some_table&#8221;</p>
<p>which for portability can be written as &#8220;/*&#8221; . MYSQLND_QC_ENABLE_SWITCH . &#8220;*/&#8221;;</p>
<p>e.g.</p>
<pre class="brush: php; title: ;">
&lt;?php
$mysqli = new mysqli('127.0.0.1', 'root', '', 'war_and_peace');
$mysqli-&gt;query('RESET QUERY CACHE');
$querySQL = &quot;SELECT * FROM words WHERE word = 'sausage' &quot;;
$time_start = microtime(true);
if ($results = $mysqli-&gt;query($querySQL)) {
	echo &quot;Cold got {$results-&gt;num_rows} results in &quot;;
 	echo microtime(true) - $time_start,&quot;s&quot;,PHP_EOL;
    $results-&gt;close();
}
$querySQL = &quot;SELECT * FROM words WHERE word = 'sausage' &quot;;
$time_start = microtime(true);
if ($results = $mysqli-&gt;query($querySQL)) {
        echo &quot;Server cache got {$results-&gt;num_rows} results in &quot;;
        echo microtime(true) - $time_start,&quot;s&quot;,PHP_EOL;
    $results-&gt;close();
}
$querySQL = &quot;/*&quot; . MYSQLND_QC_ENABLE_SWITCH . &quot;*/&quot;;
$querySQL .= &quot;SELECT * FROM words WHERE word = 'sausage' &quot;;
$mysqli-&gt;query($querySQL);
$time_start = microtime(true);
if ($results = $mysqli-&gt;query($querySQL)) {
        echo &quot;Client cache got {$results-&gt;num_rows} results in &quot;;
        echo microtime(true) - $time_start,&quot;s&quot;,PHP_EOL;
    $results-&gt;close();
}
</pre>
<p>Running this script will show an even better speed improvement.</p>
<pre class="brush: bash; title: ;">
$ php MySQL_QueryCache_mysqlnd_qc.php
Cold got 5 results in 0.1253068447113s
Server cache got 5 results in 0.00036311149597168s
Client cache got 5 results in 9.8943710327148E-5s
</pre>
<h3>Win Win Win!</h3>
<p>This is pretty impressive!  This is using the default settings for the length of cache or time to live. The default setting is 30 seconds and it is set with the ini setting mysqlnd_qc.ttl. Of course after our 30 seconds are up the server cache is still there so we will still be able to make use of that. So in a way we can think of mysqlnd_qc as a way of protecting the db server from excessive repeated queries.</p>
<h3>More Options</h3>
<p>We are using the default handler which behaves in a similar way to the query cache in the mysql server. There are also other backends available such as APC, memcache and sqlite. Sqlite may well be an excellent choice even though using another db may seem a little weird, the reason is that the results sets are in the form of table data which fits well with sqlite. There is also the possibility of creating you own user handler which can use a custom invalidation algorithm there is an example at <a href="http://uk3.php.net/manual/en/mysqlnd-qc.set_user_handlers.php" onclick="pageTracker._trackPageview('/outgoing/uk3.php.net/manual/en/mysqlnd-qc.set_user_handlers.php?referer=');">http://uk3.php.net/manual/en/mysqlnd-qc.set_user_handlers.php</a> </p>
]]></content:encoded>
			<wfw:commentRss>http://fishtrap.co.uk/blog/2011/11/22/mysqlnd_qc-query-caching-in-the-client/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Parallel PHP processes with pcntl_fork</title>
		<link>http://fishtrap.co.uk/blog/2011/10/04/parallel-php-processes-with-pcntl_fork/</link>
		<comments>http://fishtrap.co.uk/blog/2011/10/04/parallel-php-processes-with-pcntl_fork/#comments</comments>
		<pubDate>Tue, 04 Oct 2011 17:07:41 +0000</pubDate>
		<dc:creator>nat</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[maths]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://fishtrap.co.uk/?p=828</guid>
		<description><![CDATA[Forking the PHP process requires the pcntl extension. This extension is limited to *nix operating systems. Once installed the key function is pcntl_fork(). The manual contains this excellent example of its use $pid = pcntl_fork(); if ($pid == -1) { &#8230; <a href="http://fishtrap.co.uk/blog/2011/10/04/parallel-php-processes-with-pcntl_fork/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://fishtrap.co.uk/wp-content/uploads/2011/10/fork_t.jpg"><img class="alignright size-full wp-image-834" src="http://fishtrap.co.uk/wp-content/uploads/2011/10/fork_t.jpg" alt="" width="200" height="133" /></a></p>
<p>Forking the PHP process requires the pcntl extension. This extension is limited to *nix operating systems. Once installed the key function is pcntl_fork(). The manual contains this excellent example of its use</p>
<pre class="brush: php; title: ;">
$pid = pcntl_fork();
 if ($pid == -1) {
      die('could not fork');
 } else if ($pid) {
 // we are the parent
     pcntl_wait($status); //Protect against Zombie children
 } else {
      // we are the child
 }
</pre>
<p>if we insert a known delay in there and time it we can get an idea of whether we are running in parallel.</p>
<pre class="brush: php; title: ;">
$pid = pcntl_fork();
 if ($pid) {
      sleep(10);
     pcntl_wait($status);
} else {
     sleep(10);
}
</pre>
<pre class="brush: bash; title: ;">
Mr-McHughs-MacBook-Pro:$ time php pcntl_fork.php
real	0m10.060s
user	0m0.020s
sys	0m0.025s
</pre>
<p>Excellent so it would appear we are running two PHP processes in parallel. Using a sleep() in this way we model an expensive and parallelisable function call for instance a heavy calculation or http request. By using a known delay instead of the real call we can work out how long it should take to execute and check our logic.</p>
<h3>What about more than two processes</h3>
<p>The first thing I tried was to put the previous code in a for loop with a couple of obvious alterations</p>
<pre class="brush: php; title: ;">
for ($i=0; $i &lt; 5; $i++) {
        $pid = pcntl_fork();
        if ($pid) {
                pcntl_wait($status);
        } else {
                echo 'starting child ',$i,PHP_EOL;
                sleep(10);
                die();
        }
}
</pre>
<p>The major alteration you will notice is that we exit or die after each child has done it&#8217;s thing. Otherwise each child will go through the remaining loops of the for loop and the script will run for a very long time. The other change is that we are no longer doing any work in the parent. There is no real reason for this other than we would always have to remember to add one to the the number of calls we were expecting to make. Even with these alterations this script has a major problem, one, that you get a good idea about if you watch it run.</p>
<pre class="brush: bash; title: ;">
Mr-McHughs-MacBook-Pro:$ time php pcntl_fork.php
starting child 0
starting child 1
starting child 2
starting child 3
starting child 4
real	0m50.113s
user	0m0.038s
sys	0m0.056s
</pre>
<p>Watching it in the terminal it becomes obvious that each child only gets started after the previous one has finished. The problem is the call to pcntl_wait($status) in the parent section. What this is doing is waiting for each child to end and hence stopping execution of the parent until it receives a signal to say a child has finished.</p>
<p>The solution is to put all calls to pcntl_wait in the parent but outside the loop that forks each process. The above script fixed is.</p>
<pre class="brush: php; title: ;">
for ($i=0; $i &lt; 5; $i++) {
        $pid = pcntl_fork();
       if ($pid) {
        } else {
                echo 'starting child ',$i,PHP_EOL;
                sleep(10);
                die();

        }
}
for ($i=0; $i &lt;5; $i++) {
        pcntl_wait($status);
}
</pre>
<p>This way we run all 5 sleep commands in parallel</p>
<pre class="brush: bash; title: ;">
Mr-McHughs-MacBook-Pro:$ time php pcntl_fork.php
starting child 0
starting child 1
starting child 2
starting child 3
starting child 4

real	0m10.077s
user	0m0.037s
sys	0m0.056s
</pre>
<p>The neatest solution is to use an array to register the pid of each child we create and then check it to see if we have any open children.</p>
<pre class="brush: php; title: ;">
&lt;?php
$forks = array();
for ($i=0; $i &lt; 5; $i++) {
        $forks[] = $pid = pcntl_fork();
        if ($pid == -1) {
                die('could not fork');
        } else if (0 === $pid) {
                echo 'starting child ',$i,PHP_EOL;
                sleep(10);
                die();

        }
}
do {
     pcntl_wait($status);
     array_pop($forks);
} while (count($forks) &gt; 0);
</pre>
]]></content:encoded>
			<wfw:commentRss>http://fishtrap.co.uk/blog/2011/10/04/parallel-php-processes-with-pcntl_fork/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Extension to find the number of processors with PHP</title>
		<link>http://fishtrap.co.uk/blog/2011/10/03/extension-to-find-the-number-of-processors-with-php/</link>
		<comments>http://fishtrap.co.uk/blog/2011/10/03/extension-to-find-the-number-of-processors-with-php/#comments</comments>
		<pubDate>Mon, 03 Oct 2011 11:45:28 +0000</pubDate>
		<dc:creator>nat</dc:creator>
				<category><![CDATA[Hacking]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://fishtrap.co.uk/?p=814</guid>
		<description><![CDATA[While working on a script to generate fractals in PHP I wanted to try and run the intensive calculations in parallel. The script I came up with has a fair amount of overhead in spawning and managing a thread since &#8230; <a href="http://fishtrap.co.uk/blog/2011/10/03/extension-to-find-the-number-of-processors-with-php/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>While working on a script to generate fractals in PHP I wanted to try and run the intensive calculations in parallel. The script I came up with has a fair amount of overhead in spawning and managing a thread since they actually each write a file to disk. So the logical optimal number of threads was the number of available processor cores. I was surprised to find there didn&#8217;t seem to be an easy way to get the number of processors in PHP. I found a short C script that seemed to do the trick. So I knocked together a quick PHP extension called num_procs. It seems to work on linux and OSX which is good enough for me.</p>
<p>The <a href="https://github.com/natmchugh/PHP-Num-Processors" target="_blank" onclick="pageTracker._trackPageview('/outgoing/github.com/natmchugh/PHP-Num-Processors?referer=');">code is on github</a></p>
<p>To install just do </p>
<pre class="brush: bash; title: ;">
git clone git://github.com/natmchugh/PHP-Num-Processors.git
cd PHP-Num-Processors
phpize
./configure
make
sudo make install
</pre>
<p>Then add &#8230; </p>
<pre class="brush: bash; title: ;">
extension=num_procs.so
</pre>
<p>.. to your php.ini</p>
<p>It exports two functions</p>
<pre class="brush: php; title: ;">
$available = num_processors_available();
var_dump($available); // int(2)
$configured = num_processors_configured();
var_dump($configured); //int(2)
</pre>
<p>The effect of parallelising the calculations was pretty dramatic by the way speed up execution by 50% at least. I intend to write a post on that sometime.</p>
]]></content:encoded>
			<wfw:commentRss>http://fishtrap.co.uk/blog/2011/10/03/extension-to-find-the-number-of-processors-with-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Zooming in on the Mandlebrot set</title>
		<link>http://fishtrap.co.uk/blog/2011/09/25/zooming-in-on-mandlebrot-set/</link>
		<comments>http://fishtrap.co.uk/blog/2011/09/25/zooming-in-on-mandlebrot-set/#comments</comments>
		<pubDate>Sun, 25 Sep 2011 06:52:15 +0000</pubDate>
		<dc:creator>nat</dc:creator>
				<category><![CDATA[maths]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://fishtrap.co.uk/?p=794</guid>
		<description><![CDATA[Here&#8217;s a video I showed a couple of times while talking about escape time fractals in PHP. The video was made by using PHP to generate the mandlebrot set set centred on a point and the decreasing the scale logarithmically. &#8230; <a href="http://fishtrap.co.uk/blog/2011/09/25/zooming-in-on-mandlebrot-set/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a video I showed a couple of times while talking about escape time fractals in PHP. The video was made by using PHP to generate the mandlebrot set set centred on a point and the decreasing the scale logarithmically.</p>
<p>httpv://www.youtube.com/watch?v=8pAUIWYVXXM</p>
]]></content:encoded>
			<wfw:commentRss>http://fishtrap.co.uk/blog/2011/09/25/zooming-in-on-mandlebrot-set/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CURL less POST requests in PHP</title>
		<link>http://fishtrap.co.uk/blog/2011/08/12/curl-less-post-requests-in-php/</link>
		<comments>http://fishtrap.co.uk/blog/2011/08/12/curl-less-post-requests-in-php/#comments</comments>
		<pubDate>Fri, 12 Aug 2011 08:17:09 +0000</pubDate>
		<dc:creator>nat</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://fishtrap.co.uk/?p=771</guid>
		<description><![CDATA[Libcurl is a great library with a whole host of features. In PHP it is accessible with the php_curl extension. Although it&#8217;s fully features it has a rather ugly and clumsy api. Added to this php_curl is often not part &#8230; <a href="http://fishtrap.co.uk/blog/2011/08/12/curl-less-post-requests-in-php/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Libcurl is a great library with a whole host of features. In PHP it is accessible with the php_curl extension. Although it&#8217;s fully features it has a rather ugly and clumsy api. Added to this php_curl is often not part of the default install of PHP.</p>
<p>There is another option. In PHP you probably know you can do requests with the streams extension and use functions like file_get_contents to retrieve a url contents.</p>
<pre class="brush: php; title: ;">
&lt;?php
$page = file_get_contents('http://fishtrap.co.uk');
</pre>
<p>Since PHP 5.0 you can also set a stream_context to include POST data. This can include files and other multipart form data.</p>
<p>I created a short script to try add a more intuitive and usable wrapper around the functions. To use it you just need to do:</p>
<pre class="brush: php; title: ;">
&lt;?php
include('StreamsHttpPost.php');
$request = new StreamsHttpPost('http://example.com');
$data = array(
'foo' =&gt; 'bar',
'baz' =&gt; 'bat',
);
$request-&gt;addFile('picture',  'path/to/file');
$page = $request-&gt;post($data);
var_dump($request-&gt;getResponseCode()); // int(302)
</pre>
<p>This will then send a post request as if the user had submitted a form with the form fields. </p>
<p>The code is <a href="https://github.com/natmchugh/StreamsHttpPost/blob/master/StreamsHttpPOST.php" onclick="pageTracker._trackPageview('/outgoing/github.com/natmchugh/StreamsHttpPost/blob/master/StreamsHttpPOST.php?referer=');">here on github</a>. Comments, pull requests and corrections welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://fishtrap.co.uk/blog/2011/08/12/curl-less-post-requests-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Borwein&#8217;s algorithm for &#928; a PHP implementation</title>
		<link>http://fishtrap.co.uk/blog/2011/08/01/borweins-algorithm-php-implementation/</link>
		<comments>http://fishtrap.co.uk/blog/2011/08/01/borweins-algorithm-php-implementation/#comments</comments>
		<pubDate>Mon, 01 Aug 2011 16:55:34 +0000</pubDate>
		<dc:creator>nat</dc:creator>
				<category><![CDATA[Hacking]]></category>
		<category><![CDATA[maths]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://fishtrap.co.uk/?p=741</guid>
		<description><![CDATA[One of the joys of Maths is the fact that the names for things sound impressive add to that the fact that the notation can look very off putting if you you don&#8217;t know what it says and this has &#8230; <a href="http://fishtrap.co.uk/blog/2011/08/01/borweins-algorithm-php-implementation/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>One of the joys of Maths is the fact that the names for things sound impressive add to that the fact that the notation can look very off putting if you you don&#8217;t know what it says and this has the effect of making you seem very erudite when talking about it. With this in mind I thought I&#8217;d post a quick implementation of Borwein&#8217;s algorithm for convergance on &Pi;.</p>
<p>The generation of increasing digits of &Pi; is in itself completely pointless but makes an interesting area of research for mathematicians and computer scientists with parallel advances in algorithm and hardware. PHP is possibly the least suitable language to implement these computationally intense calculations. However, it is possible for todays PHP scripts to quickly generate digits that took hours of computing time in the 1950&#8242;s and 1960&#8242;s.  Borwein&#8217;s algorithm is interesting for the increasing number of correct digits it gives with each iteration. According to <a href="http://en.wikipedia.org/wiki/Borwein's_algorithm" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Borwein_s_algorithm?referer=');">wikipedia</a> the algorithm is given by starting out with:</p>
<p><img class="tex" src="http://upload.wikimedia.org/math/d/1/4/d14ae320531fc796f6ca23de6a5e66d2.png" alt=" \begin{align} a_0 &amp; = 6 - 4\sqrt{2} \\                       y_0 &amp; = \sqrt{2} - 1         \end{align} " /></p>
<p>And then iterating</p>
<p><img class="tex" src="http://upload.wikimedia.org/math/b/3/b/b3bdad5b6a1cb0680f5209f0b7ec4f82.png" alt=" \begin{align} y_{k+1} &amp; = \frac{1-(1-y_k^4)^{1/4}}{1+(1-y_k^4)^{1/4}} \\                        a_{k+1} &amp; = a_k(1+y_{k+1})^4 - 2^{2k+3} y_{k+1} (1 + y_{k+1} + y_{k+1}^2)           \end{align} " /></p>
<pre class="brush: php; title: ;">

function borwein($precision){
	// set scale with suitable spare room
	bcscale($precision+5);

	//inital conditions
	$rootTwo = bcsqrt(2);
	$a = bcsub(6, bcmul(4, $rootTwo));
	$y = bcsub($rootTwo, 1);

	//number of interations needed
	$count = floor(log($precision)/log(4));
	for($k = 0; $k &lt; $count; $k++){
		$sqrt = bcsqrt(bcsub(1,bcpow($y, 4)));
		$right = bcsqrt($sqrt);
		$top = bcsub(1, $right);
		$bottom = bcadd(1, $right);
		$y = bcdiv($top, $bottom);

		$onePlusY = bcadd(1, $y);
		$left = bcmul($a, bcpow($onePlusY, 4));
		$y2 = bcpow($y, 2);
		$power = bcpow(2, (2*$k+3));
		$expansion = bcadd($onePlusY, $y2);
		$right = bcmul($power, bcmul($y, $expansion));
		$a = bcsub($left, $right);
	}
return bcdiv(1, $a, $precision);
}
echo borwein(2037), PHP_EOL;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://fishtrap.co.uk/blog/2011/08/01/borweins-algorithm-php-implementation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Factorial class</title>
		<link>http://fishtrap.co.uk/blog/2011/07/09/factorial-class/</link>
		<comments>http://fishtrap.co.uk/blog/2011/07/09/factorial-class/#comments</comments>
		<pubDate>Sat, 09 Jul 2011 18:19:14 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://fishtrap.co.uk/?p=732</guid>
		<description><![CDATA[Earlier in the week i started experimenting with translating infinite series calculations for the value of &#928; into php. I started with the Chudnovsky brothers algorithm which I understood to be the fastest. As you will see extensive use of &#8230; <a href="http://fishtrap.co.uk/blog/2011/07/09/factorial-class/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Earlier in the week i started experimenting with translating infinite series calculations for the value of &Pi; into php. I started with the <a href="http://en.wikipedia.org/wiki/Pi#Computation_in_the_computer_age" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Pi_Computation_in_the_computer_age?referer=');">Chudnovsky brothers algorithm</a> which I understood to be the fastest.</p>
<p><a href="http://fishtrap.co.uk/wp-content/uploads/2011/07/08ea94b2c5878f0d27f1b867293fb6b0.png"><img src="http://fishtrap.co.uk/wp-content/uploads/2011/07/08ea94b2c5878f0d27f1b867293fb6b0.png" alt="" width="441" height="51" class="aligncenter size-full wp-image-736" /></a></p>
<p>As you will see extensive use of factorials is made. I was using the bc extension for PHP which does not have a simple way of calculating factorials. I came up with the following class to try and calculate them efficiently from the nearest previously calculated. Using it I was able to cut the calculation time for 2037 digits in half.</p>
<pre class="brush: php; title: ;">
&lt;?php

class Factiorial {

	private static $_cache = array(1 =&gt; 1);

	public function calculate($n) {
		$nearest = $this-&gt;findNearestInCache($n);
		$answer = self::$_cache[$nearest];
		$diff = $n - $nearest;
		if ($diff &gt; 0) {
			for ($i = $nearest; $i &lt; $n; ++$i) {
				$answer = bcadd($answer, bcmul($answer,$i));
				self::$_cache[$i+1] = $answer;
			}
		} else {
			for ($i = $nearest; $i &gt; $n; --$i) {
				$answer = bcdiv($answer,$i);
			}
		}
		return $answer;
	}

	private function findNearestInCache($n) {
		$keys = array_keys(self::$_cache);
		rsort($keys);
		$nearest = current($keys) ;
		$smallestDiff = abs(current($keys) - $n);
			foreach ($keys as $key) {
				if ($diff = abs($n - $key) &lt; $smallestDiff) {
					$nearest = $key;
					$smallestDiff = $diff;
				}
			}
			return $nearest;
	}
}
</pre>
<p>This only really works because we are calculating successive factorials and will often be calculating the same value several times. Having arrays of several thousand items in the cache could be quite slow so I tried limiting the size of the cache array but the extra bookkeeping overhead proved to slow the script down.</p>
]]></content:encoded>
			<wfw:commentRss>http://fishtrap.co.uk/blog/2011/07/09/factorial-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Compiling PHP to use mysqlnd on ubuntu</title>
		<link>http://fishtrap.co.uk/blog/2011/06/16/compiling-php-to-use-mysqlnd-on-ubuntu/</link>
		<comments>http://fishtrap.co.uk/blog/2011/06/16/compiling-php-to-use-mysqlnd-on-ubuntu/#comments</comments>
		<pubDate>Thu, 16 Jun 2011 16:47:39 +0000</pubDate>
		<dc:creator>nat</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[mysqlnd]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://fishtrap.co.uk/?p=716</guid>
		<description><![CDATA[Distro maintainers seem to be a little slow in using mysqlnd. I guess they have their own ideas and needs. The best way I&#8217;ve found of installing mysqlnd on ubuntu is to use dpkg to rebuild the .deb. Of course &#8230; <a href="http://fishtrap.co.uk/blog/2011/06/16/compiling-php-to-use-mysqlnd-on-ubuntu/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Distro maintainers seem to be a little slow in using mysqlnd. I guess they have their own ideas and needs. </p>
<p>The best way I&#8217;ve found of installing mysqlnd on ubuntu is to use dpkg to rebuild the .deb. Of course this will need to be done when ever you update the PHP package so is not recomended for anything other than experimental servers.</p>
<p>Quick step by step</p>
<p>Install everything needed to compile C code</p>
<pre class="brush: bash; title: ;">
sudo apt-get install build-essential debhelper
</pre>
<p>Install any special depandancies for building PHP such as bison</p>
<pre class="brush: bash; title: ;">
sudo apt-get build-dep php5
</pre>
<p>Install the PHP source for the current PHP package</p>
<pre class="brush: bash; title: ;">
sudo apt-get source php5
</pre>
<p>This will download the source code for your PHP version into the current directory</p>
<pre class="brush: bash; title: ;">
cd php5-5.3.2/
</pre>
<p>Then edit the file debian/patches/series or in older ubuntu releases debian/patches/order</p>
<pre class="brush: bash; title: ;">
sudo vim debian/patches/series
</pre>
<p>remove the lines<br />
force_libmysqlclient_r.patch<br />
and while we&#8217;re at it remove this line which removes the config flags from phpinfo() apparently done by debian to stop false bug reports but quite annoying<br />
052-phpinfo_no_configure.patch</p>
<p>then edit the rules file</p>
<p><del datetime="2011-07-26T08:00:11+00:00">sudo vim debian/patches/rules</del></p>
<pre class="brush: bash; title: ;">
sudo vim debian/rules
</pre>
<p>search for<br />
&#8211;with-mysql=shared, /usr \<br />
replace with<br />
 &#8211;with-mysql=mysqlnd \</p>
<p>same with<br />
&#8211;with-mysqli=shared, /usr \<br />
replace with<br />
 &#8211;with-mysqli=mysqlnd \</p>
<p>make &#8211;enable-pdo=shared or &#8211;with-pdo=shared \</p>
<p>into &#8211;with-enable or &#8211;with-pdo</p>
<p>and<br />
&#8211;with-pdo-mysql=shared, /usr \<br />
into<br />
&#8211;with-pdo-mysql=mysqlnd \</p>
<p>This will build mysql as a static module rather than load it dynamically this will save building each mysql extension separately with mysqlnd</p>
<p>stop the tests running by exporting an environment variable</p>
<pre class="brush: bash; title: ;">
export DEB_BUILD_OPTIONS=nocheck
</pre>
<p>Now build the package</p>
<pre class="brush: bash; title: ;">
sudo dpkg-buildpackage
</pre>
<p>Go and do something else for a little while.</p>
<p>Once done if you</p>
<pre class="brush: bash; title: ;">
cd ..
ls
</pre>
<p>You should see a big list of debs</p>
<p>dpkg the ones you need such as</p>
<pre class="brush: bash; title: ;">
sudo dpkg -i php5-common_5.3.2-1ubuntu4.9_amd64.deb
sudo dpkg -i libapache2-mod-php5_5.3.2-1ubuntu4.9_amd64.deb
</pre>
<p>bingo the output of phpinfo() and php -m should confirm you have mysqlnd installed</p>
]]></content:encoded>
			<wfw:commentRss>http://fishtrap.co.uk/blog/2011/06/16/compiling-php-to-use-mysqlnd-on-ubuntu/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>

