<?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>Streaky's Blog &#187; PHP</title>
	<atom:link href="http://mybrokenlogic.com/category/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://mybrokenlogic.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Mon, 19 Jul 2010 21:50:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Validating Email w/PHP</title>
		<link>http://mybrokenlogic.com/2010/07/15/validating-email-wphp/</link>
		<comments>http://mybrokenlogic.com/2010/07/15/validating-email-wphp/#comments</comments>
		<pubDate>Thu, 15 Jul 2010 13:44:58 +0000</pubDate>
		<dc:creator>streaky</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Work]]></category>

		<guid isPermaLink="false">http://mybrokenlogic.com/?p=91</guid>
		<description><![CDATA[Just came up with a fairly smart way to validate email that removes a few issues generally caused by this sort of stuff. It&#8217;s not totally complete and it&#8217;s obviously part of a validation class &#8211; anybody planning on using it will need to modify it to make it work to their needs. I return [...]]]></description>
			<content:encoded><![CDATA[<p>Just came up with a fairly smart way to validate email that removes a few issues generally caused by this sort of stuff. It&#8217;s not totally complete and it&#8217;s obviously part of a validation class &#8211; anybody planning on using it will need to modify it to make it work to their needs.<span id="more-91"></span></p>
<p>I return a value so the class which calls this can replace the value back in the form if there is an error, and it actually replaces it in the data that is used (sent to the DB or whatever), I also use a custom validation exception class, these are all things that will need to be considered if anybody who sees it plans on using. Caveat emptor and whatnot.</p>
<p>What it does is sends the value to the PHP filter functions for validating as looking remotely like an email address, which is handy but it will validate local addresses and for domains that don&#8217;t exist.</p>
<p>What my code does is check if there is a remote address part and then if it is an IP just allows it, if it&#8217;s a domain it checks if the domain has MX records using <a href="http://php.net/manual/en/function.checkdnsrr.php" target="_blank">checkdnsrr()</a> &#8211; if that&#8217;s all good it allows it.</p>
<p>What could be improved? It doesn&#8217;t work so well at preventing local IP addresses going through. It also won&#8217;t tell you if the user is legit at a given domain or if the user has any association at all, so address validation will be a must in some circumstances, but it will prevent the standard dfgdf@dfdgdf.com type stuff. At least you&#8217;ll know if the domain part looks even close to reasonable, which is one of the &#8216;failings&#8217; (read: missing features?) of FILTER_VALIDATE_EMAIL if you want internet-only addresses entering.</p>
<pre class="brush: php;">	public function email_address($value) {
		$result = filter_var($value, FILTER_VALIDATE_EMAIL);
		if($result == false) {
			throw new validateException(&quot;Invalid email address&quot;);
		}
		$domain = explode(&quot;@&quot;, $value, 2);
		if(filter_var($domain[1], FILTER_VALIDATE_IP) !== false) {
			return $value;
		}
		if(checkdnsrr($domain[1]) == false) {
			throw new validateException(&quot;Email domain doesn't seem to exist or is incapable of recieving mail&quot;);
		}
		return $value;
	}</pre>
]]></content:encoded>
			<wfw:commentRss>http://mybrokenlogic.com/2010/07/15/validating-email-wphp/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Next Generation Pastebins</title>
		<link>http://mybrokenlogic.com/2010/03/06/next-generation-pastebins/</link>
		<comments>http://mybrokenlogic.com/2010/03/06/next-generation-pastebins/#comments</comments>
		<pubDate>Sat, 06 Mar 2010 21:55:25 +0000</pubDate>
		<dc:creator>streaky</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Paste2.org]]></category>

		<guid isPermaLink="false">http://mybrokenlogic.com/?p=47</guid>
		<description><![CDATA[It&#8217;s been my goal since the day I started paste2 to figure out how I can bring something new to the pastebin concept. I&#8217;ve targetted performance (already fast, but improved again in the new code), tried to make the interface as uncluttered as possible (which is also much improved in the new code) and paste2 [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been my goal since the day I started paste2 to figure out how I can bring something new to the pastebin concept. I&#8217;ve targetted performance (already fast, but improved again in the new code), tried to make the interface as uncluttered as possible (which is also much improved in the new code) and paste2 is about to get the <a href="http://www.akamai.com/" target="_blank">Akamai</a> treatment on it&#8217;s assets with the new code. Not wanting to just compete and be like other pastebins, I&#8217;ve been trying to figure out &#8211; for over 3 years now in fact, where pastebins should go next. I&#8217;m absolutely convinced now that the next step for pastebins is &#8216;live&#8217;  real-time collaberative editing.</p>
<p>After seeing this happening in a IRC channel not long back, being done inside <a href="http://etherpad.com/" target="_blank">an editor</a> that is really designed for creating word processed style documents, but with code, I&#8217;m absolutely sure it&#8217;s the way forward.</p>
<p>The problem of course is that this stuff isn&#8217;t easy. I already have a plan to do it using some parts of google mobwrite, and building the server side in PHP because it&#8217;ll be faster &#8211; and I&#8217;ll trust myself more if a bug comes up to know the language ins and outs, which while I can write Python I don&#8217;t really trust it or myself. I could easily just do it easily using mobwrite in it&#8217;s entirety but the performance wouldn&#8217;t be great, and like I said &#8211; if something came up it&#8217;d probably push my Python knowledge.</p>
<p>Problem is getting it done. I was thinking about (and started) writing the whole thing into the new code, but I&#8217;ve changed my mind &#8211; I&#8217;m going to push the new code out on the new application server, then start working on that.</p>
<p>There&#8217;s some other good pastebins around, since paste2 came on the scene (at the time pastebin.com was down basically all the time) some other new ones have popped up and are helping improve the competition in the &#8216;market&#8217;, which can&#8217;t be a bad thing. Even pastebin.com has had a redesign now (after <a href="http://blog.dixo.net/2010/02/19/pastebin-com-has-a-new-owner/" target="_blank">being sold</a>).</p>
]]></content:encoded>
			<wfw:commentRss>http://mybrokenlogic.com/2010/03/06/next-generation-pastebins/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>PHP Application Server &#8211; Update</title>
		<link>http://mybrokenlogic.com/2009/11/22/php-application-server-update/</link>
		<comments>http://mybrokenlogic.com/2009/11/22/php-application-server-update/#comments</comments>
		<pubDate>Sun, 22 Nov 2009 19:19:01 +0000</pubDate>
		<dc:creator>streaky</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://mybrokenlogic.com/?p=27</guid>
		<description><![CDATA[So this project got sort of abandoned due to a really horrible potential issue I thought of, the new job taking up a lot of time and just general roadblocks. It&#8217;s now been brought back from the dead, like Frankenstein. I&#8217;ve been trying to fix a problem I thought of in my head, sort of [...]]]></description>
			<content:encoded><![CDATA[<p>So this project got sort of abandoned due to a really horrible potential issue I thought of, the new job taking up a lot of time and just general roadblocks.</p>
<p>It&#8217;s now been brought back from the dead, like Frankenstein.</p>
<p>I&#8217;ve been trying to fix a problem I thought of in my head, sort of a &#8220;how the hell am I going to solve this problem?&#8221; type deal.</p>
<p>The problem being essentially, because you maintain a connection with the DB server (because the application is persistent), if it gets restarted the application flaps &#8211; because the server kills the connections. It&#8217;s not really feasible to ask people to try/catch the specific exception, and because of one of the features of the server that isn&#8217;t available anywhere else (it&#8217;s essentially a minimal preforking HTTPD &#8211; though not intended to be used as one, I&#8217;m actually considering killing the process if there&#8217;s no forwarded-for header &#8211; to make it a &#8220;on your head be it&#8221; type deal), it&#8217;s very hard to catch this stuff further up the stack. You can&#8217;t just pretend it&#8217;s not happening and kill the child when you&#8217;re working with a forked server like this &#8211; if you have 10 children you&#8217;re going to output errors for 10 clients which is not really what you want to be doing.</p>
<p>I experimented with using semaphores to resolve the issue, which didn&#8217;t work too well and was kind of ugly &#8211; and it made the code that much more complex.</p>
<p>The solution I came up with was to catch the problem in the PDO class (currently only for MySQL), and create a new kind of exception that gets caught in the routing code (the chunk of code that decides where requests get sent). This then redirects the client to the same page (302/Location headers) and kills the child, the system then does what it usually does when children die &#8211; fires up a new child, which creates a new instance of the app class &#8211; which will reconnect to MySQL.</p>
<p>It also shows you the problem with being very hands-off with what people who use systems you write, if you&#8217;re not paying attention you can create problems that you don&#8217;t anticipate then the day you let people play with it somebody restarts a server in production and the world ends. So you basically have to force people to work like you want them to.</p>
]]></content:encoded>
			<wfw:commentRss>http://mybrokenlogic.com/2009/11/22/php-application-server-update/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Paste2.org Updates</title>
		<link>http://mybrokenlogic.com/2009/02/18/paste2org-updates/</link>
		<comments>http://mybrokenlogic.com/2009/02/18/paste2org-updates/#comments</comments>
		<pubDate>Wed, 18 Feb 2009 17:47:56 +0000</pubDate>
		<dc:creator>streaky</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Paste2.org]]></category>
		<category><![CDATA[application server]]></category>
		<category><![CDATA[emacs]]></category>

		<guid isPermaLink="false">http://mybrokenlogic.com/?p=10</guid>
		<description><![CDATA[So I&#8217;ve been working on a major Paste2.org update for a while now. One of the major things I&#8217;m currently doing with it is making it work in the application server I described in my previous post. The improvements in performance will mean it&#8217;ll scale to the traffic increases it&#8217;s been getting for some time [...]]]></description>
			<content:encoded><![CDATA[<p>So I&#8217;ve been working on a major <a href="http://paste2.org/" target="_blank">Paste2.org</a> update for a while now. One of the major things I&#8217;m currently doing with it is making it work in the application server I <a href="http://mybrokenlogic.com/2009/02/18/back-in-the-game-with-1-swing/" target="_blank">described in my previous post</a>. The improvements in performance will mean it&#8217;ll scale to the traffic increases it&#8217;s been getting for some time to come without needing to upgrade it&#8217;s infrastructure. A few times paste2 has came very close to breaking into the top 10k sites in the Alexa rankings, and consistently hanging around the 20k mark, meaning it&#8217;s my most successful personally-owned site to date. To some people it might not be that impressive but I guess it&#8217;s a bit of a milestone for sites I personally own.</p>
<p>I&#8217;ve also either added or are working on adding a few new features.<span id="more-10"></span></p>
<div id="attachment_11" class="wp-caption alignright" style="width: 160px"><a href="http://mybrokenlogic.com/wp-content/uploads/2009/02/p2-new-screenshot.png"><img class="size-thumbnail wp-image-11" title="New Screenshot (paste2.org)" src="http://mybrokenlogic.com/wp-content/uploads/2009/02/p2-new-screenshot-150x150.png" alt="Screenshot of the new template, I know, the logo is horrible!" width="150" height="150" /></a><p class="wp-caption-text">Screenshot of the new template, I know, the logo is horrible!</p></div>
<p>The first one that&#8217;s pretty much done is diffing between pastes. Essentially you can diff between pastes and in the page you&#8217;d be able to quickly, on the click of one button, be able to show the diff of the two pastes without messing around entering numbers.</p>
<p>Secondly the site has a new theme that I&#8217;m pretty happy with now. It&#8217;s lighter and much cleaner, and will hopefully provide a better experience for users.</p>
<p>I also want to add (text) file uploading to paste2 when creating pastes. When you have a big file pasting it in a browser window can be really annoying.</p>
<p>Another major project I want to do is to have a remote API using probably <a href="http://en.wikipedia.org/wiki/SOAP" target="_blank">SOAP</a> for people that want to create tools for interacting with the site.</p>
<p>I&#8217;ll be trying to get a beta up as soon as I can but some current work commitments mean I can&#8217;t spend as much time on it as I&#8217;d like.</p>
<p>On the note of scripts interacting with paste2 I was contacted by <a href="http://www.emacswiki.org/emacs/AndyStewart" target="_blank">Andy Stewart</a> regarding the Emacs script he created for interacting with paste2.org. After a few emails back and forth I implemented a feature for getting raw content of pastes so they can be grabbed by <a href="http://www.emacswiki.org/cgi-bin/emacs/Paste2" target="_blank">his script</a>. I don&#8217;t use Emacs personally, but it looks useful.</p>
]]></content:encoded>
			<wfw:commentRss>http://mybrokenlogic.com/2009/02/18/paste2org-updates/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Persistant PHP Application Server</title>
		<link>http://mybrokenlogic.com/2009/02/18/a-persistant-php-app-server/</link>
		<comments>http://mybrokenlogic.com/2009/02/18/a-persistant-php-app-server/#comments</comments>
		<pubDate>Wed, 18 Feb 2009 09:37:19 +0000</pubDate>
		<dc:creator>streaky</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[application server]]></category>
		<category><![CDATA[prepared statements]]></category>
		<category><![CDATA[Work]]></category>

		<guid isPermaLink="false">http://mybrokenlogic.com/?p=3</guid>
		<description><![CDATA[What I really wanted to talk about is an application server that I wrote for PHP.  The problem I identified a while back is when I&#8217;m writing code in PHP the thing I&#8217;m doing most of the time is writing web applications. Now PHP is usually fast, at least that is, when you&#8217;re not writing [...]]]></description>
			<content:encoded><![CDATA[<p>What I really wanted to talk about is an application server that I wrote for <a href="http://en.wikipedia.org/wiki/PHP" target="_blank">PHP</a>.  The problem I identified a while back is when I&#8217;m writing code in PHP the thing I&#8217;m doing most of the time is writing web applications. Now PHP is usually fast, at least that is, when you&#8217;re not writing huge sites that take a lot of requests. The way PHP is normally, historically, implemented is for every page request you have to build up and tear down your application, and with some SAPIs you have to also build up and tear down the PHP binary on top.</p>
<p>That presents a problem for performance, in that every time somebody requests a page you&#8217;re doing a lot of work to get the application to a state where it can start spitting out content &#8211; then at the end throwing away all that hard work you did. It wastes physical time and CPU cycles, not forgetting often IO and memory in the process. To resolve the issue you have to make your application persistent, which is something that PHP isn&#8217;t designed for in this context.<span id="more-3"></span></p>
<p>A while back I discovered that somebody wrote an <a href="http://code.google.com/p/appserver-in-php/" target="_blank">SCGI handler in PHP</a> &#8211; so that you can write your application in a way that you build it up and it serves requests from it&#8217;s already-running state, your HTTP server talks to your application via the SCGI class and dumps this output back to the HTTP server and handles the next request without it all being torn down. That&#8217;s useful, it&#8217;s what you want when you&#8217;re serving huge numbers of requests in short spaces of my time. The problem is this isn&#8217;t a complete answer to the issue.</p>
<p>Firstly the code can only handle 1 request at a time. If a concurrent request comes in it&#8217;ll get queued by the HTTP server until the previous request has finished. This is easy enough to resolve &#8211; if your HTTP server supports it you can just spawn multiple instances and make it round-robin the backends. Another problem is these different processes don&#8217;t know about each other, they&#8217;re completely dumb to the fact that there are more versions of themselves running &#8211; they can&#8217;t share data with their siblings, and if you want to have a process to watch over them and make sure everything is fine you need to write that code separately. Then you get even more problems if your traffic gets to the point where it&#8217;s too much for the number of processes you have spawned; you need to manually increase the number of processes.</p>
<p>I decided I needed to come up with a solution to the problem.</p>
<p>First on my agenda was to ensure it spoke a language that most if not all HTTP servers understand. SCGI is pretty well supported, but not by everything. FCGI uses a complex binary communications protocol, which is a good protocol and it&#8217;s well supported &#8211; the problem is when you&#8217;re attacking a problem like this you have no idea if in the end your solution is going to improve things at all &#8211; so it&#8217;s potentially a complete waste of time trying to implement a protocol if the project fails.</p>
<p>I settled with making the server code support HTTP, which aside from the fact it&#8217;s well supported, has other fringe benefits. Firstly you can point a browser at the application and test the code directly with no HTTPD needed, which creates all sorts of opportunities for doing fun things when debugging, not least because you can find out if your problem is caused by your code or the HTTP server. You can also stick hardware load balancers in between your frontend HTTP server and backend slave application servers if you need that kind of capacity. HTTP load balancers are easy to get hold of. You can even put squid between the app server backend(s) and the frontend HTTP server if you need to without making <em>any</em> changes to your code if you need to. Now bear in mind this is was never intended to be exposed to browsers directly, just you can because it speaks HTTP 1.1 &#8211; but it&#8217;s not the idea. This is not a HTTP server in it&#8217;s own right, not even close., it isn&#8217;t intended to be used this way. This is not <a href="http://nanoweb.si.kz/" target="_blank">Nanoweb</a>.</p>
<p>The next step is was to resolve the 1 connection at a time issue. Unfortunately PHP doesn&#8217;t support threads in any kind of way, shape or form. It&#8217;s not the end of the world, but despite there being a PECL extension covering threads this isn&#8217;t going to work, it hasn&#8217;t been updated in years &#8211; and even when it was updated it never gone finished, which is a huge shame. Hopefully one day somebody recovers that extension because it has huge potential outside the traditional &#8220;PHP does this and only this&#8221; worldview.</p>
<p>The only opportunity for doing this stuff in PHP is to use pcntl_fork(), so I hacked in some forking code. Experience teaches me that it&#8217;s not sensible to fork our server on every request &#8211; you have to fork enough children to handle your load up-front. What I was left with after a few hours was a HTTP server class that is extended extend by your application class, in a similar way to the application server I found previously &#8211; you write a constructor that builds up stuff you always need, maybe a template engine, read in some data files, connect to a DB and whatever, then it returns to the server class which forks the process into a bunch of children. When a request comes in i hits one of the children which processes the HTTP headers and body (if it&#8217;s a POST), which in turn passes the request off to your code.</p>
<p>After bashing it with ab it was clearly very fast, stable and working well. The result was a fully-functioning web application (a rebuild of paste2.org) spitting out it&#8217;s home page in about 0.0004s on my crappy local development server. For the sake of unscientific comparison, the &#8216;same&#8217; code on paste2&#8242;s production server manages to spit out the same page in about 0.01s. That&#8217;s a pretty major time improvement, on significantly worse hardware.</p>
<p>It has a few issues still else I&#8217;d be putting the code up for people to look at &#8211; they&#8217;re all solvable though with a bit of time which I don&#8217;t really have right now. The first is some of the code is a mess as it is. The second one is if MySQL (or more accurately, I&#8217;m using PDO right now, hence whatever you use) goes away the code isn&#8217;t aware and tries to keep banging away at the old connection/prepared statement &#8211; but that&#8217;s going to be easy to resolve. The next issue is I haven&#8217;t added any kind of communication between processes yet but that&#8217;s just a matter of getting to it, and the code doesn&#8217;t need it &#8211; it will just add more reasons to use it. Basically right now it&#8217;s not even as cool as it could be.</p>
<p>Another problem is that no opcode cacher for PHP supports CLI as far as I can see, not because of technical difficulties but that they, I guess, have been completely useless in the past. The reason why this would be useful is that some template engines (including mine) repeatedly try to include the same file which it seems isn&#8217;t cached anywhere. That could be speeded up by an opcode cacher. I could use the CGI SAPI or patch <a href="http://xcache.lighttpd.net/" target="_blank">XCache</a> and give it a try, and then see what happens. [<strong><em>Update</em></strong>: I tried this with APC in CGI SAPI instead of CLI and it does improve things, but with the nature of the beast <em>milage may vary</em>].</p>
<p>The last issue I can think of is that I haven&#8217;t written in a way yet for the code to monitor itself and spawn new children when it gets clogged up or kill off children when it has too many. It does spawn new children when another dies though, that is to say it ensures there&#8217;s always x children spawned.</p>
<p>Because the app is persistent there&#8217;s some other fringe benefits that one might not usually think about.</p>
<p>Around the time I was hacking this together, in ##php on Freenode, Rasmus was complaining about how there&#8217;s no cache for prepared statements in MySQL. A few hours later it occurred to me that because what I&#8217;ve been doing is persistent across requests and that it holds open connections to the database server if you make your app work that way (and you want it to work that way) it&#8217;d be possible to implement something resembling a prepared statement &#8216;cache&#8217;. I should say before I get slapped around for what follows &#8211; I know what I&#8217;m about to describe isn&#8217;t <em>actually</em> a cache but it&#8217;s the next-best thing.</p>
<p>I pulled out the application-specific PDO code from my test application (the paste2.org rebuild), and moved it to the main app server parent class. Then I added two methods, one creates a prepared statement from a string and an identifier string (whatever you like as long as it works as a PHP array key) and stores it, the other returns a reference to the &#8216;named&#8217; prepared statement. Essentially you can now add prepared statements in your app&#8217;s constructor (or wherever, realistically) and reuse them time-after-time-after-time.</p>
]]></content:encoded>
			<wfw:commentRss>http://mybrokenlogic.com/2009/02/18/a-persistant-php-app-server/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
