<?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>Andrew's Tech Musings &#187; Andrew Curioso</title>
	<atom:link href="http://andrewcurioso.com/author/admin/feed/" rel="self" type="application/rss+xml" />
	<link>http://andrewcurioso.com</link>
	<description>Tech, Social Media, PHP, Opinions</description>
	<lastBuildDate>Wed, 12 Oct 2011 19:43:27 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Counting to 1000 in PHP without loops or conditionals</title>
		<link>http://andrewcurioso.com/2011/03/counting-to-1000-in-php-without-loops-or-conditionals/</link>
		<comments>http://andrewcurioso.com/2011/03/counting-to-1000-in-php-without-loops-or-conditionals/#comments</comments>
		<pubDate>Tue, 15 Mar 2011 00:54:45 +0000</pubDate>
		<dc:creator>Andrew Curioso</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[hacking]]></category>

		<guid isPermaLink="false">http://andrewcurioso.com/?p=690</guid>
		<description><![CDATA[Update: added a benchmark for performance comparison and updated the code to no longer rely on a fatal error to exit. It started with one question: Print numbers from 1 to 1000 without using any loop or conditional statements. Don&#8217;t just write the printf() or cout statement 1000 times. How would you do that using [...]]]></description>
			<content:encoded><![CDATA[<p class="update"><strong>Update:</strong> added a benchmark for performance comparison and updated the code to no longer rely on a fatal error to exit.</p>
<p>It started with one question:</p>
<blockquote><p>
Print numbers from 1 to 1000 without using any loop or conditional statements. Don&#8217;t just write the printf() or cout statement 1000 times.</p>
<p>How would you do that using C or C++?<br />
<a class="citation" href="http://stackoverflow.com/questions/4568645/printing-1-to-1000-without-loop-or-conditionals/4583502">Source: Stack Overflow</a>
</p></blockquote>
<p>My favorite answer was an amazing example of obscure C. Using math to iterate between two function pointers (printf and exit). And while it brought back memories of my C days, I kind of left it at that.</p>
<p>Later in the day, one of my co-workers messaged me with his version of a 1-1000 iterator in PHP. So naturally, I had to write my own version.</p>
<p><span id="more-690"></span></p>
<p>Remember the rules: no control loops and no conditionals.</p>
<p>I hammered out a quick example using an array to simulate the pointer technique used in my favorite C-language solution. It was 10 lines of code. I managed to break it down to one function call:</p>
<pre class="brush: php; title: ; notranslate">
call_user_func( $x = function( $f, $i=1 ) {
  echo &quot;$i\n&quot;, $f[floor($i/1000)]($f, ++$i);
}, array( $x, function(){} ));
</pre>
<p>Try it. Assuming that you have PHP 5.3 for the lambda functions, it will work. Now to break down why it works:</p>
<p>The call_user_function call takes a callback as the first parameter and passes all subsequent parameters directly to the callback. A callback in PHP can be a string, array, or lambda function. I&#8217;m using the later here.</p>
<p>My lambda function takes two parameters. An array and a counter. If the counter is not specified it will default to one. The trickier part is the array. In this case it is an array of functions. My function is recursive so the array needs to reference it. By taking advantage of the left-to-right nature of PHP, I am assigning the function to the variable $x prior to the array being constructed.</p>
<p>Now, inside my function I am echoing the value of $i and the return value of the recursive function (which is undefined&#8230; it&#8217;s just a little cheat to keep it on one line).</p>
<p>Now to break down the second parameter to the echo.</p>
<p>It looks up a function in the array that is passed in. Remember, the array contains only <del>one value (the function itself)</del> two values (the function itself and an empty &#8220;exit&#8221; function). It uses the floor of $i/1000 as the array index. Which means that the value will be 0 until $i is equal to 1000. Then it passes in the array and the counter. Remember that if the &#8220;++&#8221; is before the variable then the increment will happen prior to the enclosing function being called.</p>
<p>When the index does hit 1, <del>there will be an error. I suppressed that using the &#8220;@&#8221; operator</del> it will call the empty function. At this point the recursion ends.</p>
<p>And we&#8217;re done.</p>
<h3>Benchmarks (added March 15th)</h3>
<p>This is obviously meant to be a thought exercise and not a practical thing to do in a real-world application but I thought it might be fun to run some tests against a normal loop. I upped the loop to 1,000,000 to make things more interesting. Here is my test code:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

ini_set('memory_limit', '1000M');
const COUNT = 1000000;

$t1 = 0;
$t2 = 0;

$s = microtime(true);

call_user_func( $x = function( $f, $i=1 ) {
  echo &quot;$i\n&quot;,  $f[floor($i/COUNT)]($f, ++$i);
}, array( $x, function(){} ));

$t1 = microtime(true)-$s;

$s = microtime(true);

for ( $i=0; $i&lt;COUNT; $i++ ) {
  echo &quot;$i\n&quot;;
}

$t2 = microtime(true)-$s;

echo 'Recursive: '.number_format($t1,2).&quot;s\n&quot;;
echo 'Loop: '.number_format($t2,2).&quot;s\n&quot;;
?&gt;
</pre>
<p>The results:</p>
<pre class="brush: plain; title: ; notranslate">
Recursive: 6.38s
Loop: 5.28s
</pre>
<p>Not to mention that every recursive call needs to add the current state to the stack. Which is why the memory limit is increased the the beginning of the script. So clearly it is impractical. However, I&#8217;m actually a little surprised that the results are as close at they are.</p>
]]></content:encoded>
			<wfw:commentRss>http://andrewcurioso.com/2011/03/counting-to-1000-in-php-without-loops-or-conditionals/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>FreePriceAlerts.com</title>
		<link>http://andrewcurioso.com/2011/03/freepricealerts-com/</link>
		<comments>http://andrewcurioso.com/2011/03/freepricealerts-com/#comments</comments>
		<pubDate>Thu, 10 Mar 2011 20:01:05 +0000</pubDate>
		<dc:creator>Andrew Curioso</dc:creator>
				<category><![CDATA[Portfolio]]></category>

		<guid isPermaLink="false">http://andrewcurioso.com/?p=655</guid>
		<description><![CDATA[FreePriceAlerts.com is a set of tools that help people save money while they shop. It was originally built on technologies developed for myVBO but has grown to something much more. Some of its features are: An advanced pricing engine that quickly finds the best prices from all over the Internet. Toolbars for Firefox, Safari, Chrome, [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.freepricealerts.com/">FreePriceAlerts.com</a> is a set of tools that help people save money while they shop.</p>
<p><iframe style="float: right; padding: 0 0 20px 20px;" width="420" height="315" src="http://www.youtube.com/embed/QfKgoZmiqc4" frameborder="0" allowfullscreen></iframe></p>
<p>It was originally built on technologies developed for <a href="/2010/02/myvbo/">myVBO</a> but has grown to something much more. Some of its features are:</p>
<ul>
<li>An advanced pricing engine that quickly finds the best prices from all over the Internet.</li>
<li>Toolbars for Firefox, Safari, Chrome, and Internet Explorer.</li>
<li>A mobile website.</li>
<li>Wishlists that users can create and share.</li>
</ul>
<p>My own contributions to the project include:</p>
<ul>
<li>Collaborated on the user experience and architecture design from the project start.</li>
<li>Developed a product processing infrastructure capable of handling tens of millions of products a day using Gearman as a job manager along with XSLT, AWK, Lex, and Yacc.</li>
<li>Designed a RESTful API for use by all client applications.</li>
<li>Partner integration.</li>
<li>Designed a scalable cloud based multi-tier infrastructure.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://andrewcurioso.com/2011/03/freepricealerts-com/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AccessiblePlaces.in</title>
		<link>http://andrewcurioso.com/2011/03/accessibleplaces/</link>
		<comments>http://andrewcurioso.com/2011/03/accessibleplaces/#comments</comments>
		<pubDate>Thu, 10 Mar 2011 15:52:39 +0000</pubDate>
		<dc:creator>Andrew Curioso</dc:creator>
				<category><![CDATA[Portfolio]]></category>

		<guid isPermaLink="false">http://andrewcurioso.com/?p=653</guid>
		<description><![CDATA[I had the pleasure of attending the Boston Hack Day challenge in 2011. I came without any ideas of my own. Instead, I was looking to help a team that was working on something cool and genuinely good for society. I was not disappointed. AccessiblePlaces.in is a crowd sourced website that helps people with disabilities [...]]]></description>
			<content:encoded><![CDATA[<p>I had the pleasure of attending the Boston Hack Day challenge in 2011. I came without any ideas of my own. Instead, I was looking to help a team that was working on something cool and genuinely good for society. I was not disappointed.</p>
<p><a href="http://www.accessibleplaces.in/">AccessiblePlaces.in</a> is a crowd sourced website that helps people with disabilities discover places that are accessible to them and anonymously share their experiences with other people. It is optimized to be quick and easy to use on both a mobile phone and on a computer.</p>
<p>AccessiblePlaces.in was conceived and launched during a 48-hour hack-day in Boston sponsored by the Boston Globe and Boston.com. The team consisted of <a href="http://www.anthonydeaver.com">Anthony Deaver</a>, <a href="http://www.sbisbee.com/">Sam Bisbee</a>, and myself. In total, 32 teams competed. At the end of the weekend the project was fully working and it was awarded &#8220;Best Geo-Location Hack.&#8221; It only came extremely close to being the audience choice award (only a couple votes off).</p>
<p>The site was built using jQuery Mobile for the interface. On the back-end, PHP and CouchDB were used. It was built from the ground up to have an easy to use RESTful API and stores data that is compatible with the Open Civic Data standard.</p>
<p>I was able to flex my creative muscles a bit. My personal contributions included designing the logo, writing the copy on the Boston Hack Day wiki&#8230; and of course a little PHP and Javascript.</p>
<p>The project later went on to be a finalist for a 2011 <a href="http://www.mitxawards.org/innovation/">MITX Innovation Award</a> in the &#8220;Doing Good&#8221; category. Although my direct involvement with the project was limited to the Hack Day, I am happy to have helped with such a worthy project.</p>
]]></content:encoded>
			<wfw:commentRss>http://andrewcurioso.com/2011/03/accessibleplaces/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RIA: Desktop Notifications in Google Chrome</title>
		<link>http://andrewcurioso.com/2011/01/ria-desktop-notifications-in-google-chrome/</link>
		<comments>http://andrewcurioso.com/2011/01/ria-desktop-notifications-in-google-chrome/#comments</comments>
		<pubDate>Thu, 27 Jan 2011 17:37:36 +0000</pubDate>
		<dc:creator>Andrew Curioso</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[early adopters]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://andrewcurioso.com/?p=596</guid>
		<description><![CDATA[I&#8217;ve seen a number of blog posts floating around today about GMail Desktop Notifications (here, here, here, here and here &#8212; did I miss anyone?). I tried them out myself and they are very useful. Being a rich web applications developer I, of course, wanted to figure out how it works and how I could [...]]]></description>
			<content:encoded><![CDATA[<pre style="display:none"><script type="text/javascript">
<!--
function demoCheck() {
  var c = ( window.webkitNotifications !== undefined );
  if ( !c ) alert("Your browser does not support desktop notifications using this method. Try out the demos in Google Chrome!");
  return c;
}

function demoCheckPermission() {
  if ( !demoCheck() ) return;
  switch ( webkitNotifications.checkPermission() )
  {
    case 0: // PERMISSION_ALLOWED
      alert( "Permission: allowed" );
      break;
    case 1: // PERMISSION_NOT_ALLOWED
      alert( "Permission: not allowed" );
      break;
    case 2: // PERMISSION_DENIED
      alert( "Permission: denied" );
      break;
  }
}

function demoRequestPermission() {
  if ( !demoCheck() ) return;
  webkitNotifications.requestPermission();
}

function demoNotify() {
  if ( !demoCheck() ) return;
  if ( webkitNotifications.checkPermission() == 0 )
  {
    var iconImageUrl = "http://0.gravatar.com/avatar/25c07794aa15e4173b0f8b5c3f66c66b?s=64&#038;d=http://0.gravatar.com/avatar/ad516503a11cd5ca435acc9bb6523536%3Fs%3D32&#038;r=G";
    var title = "Andrew sent you a message";
    var subTitle = "Hello world.";

    var notification = webkitNotifications.createNotification( iconImageUrl, title, subTitle );
    notification.show();
  }
  else
  {
    alert( "Please request permissions first." );
  }
}

function demoHtmlNotify() {
  if ( !demoCheck() ) return;
  if ( webkitNotifications.checkPermission() == 0 )
  {
    var url = "http://andrewcurioso.com/wp-content/custom/2011/notification.html";
    var notification = webkitNotifications.createHTMLNotification( url );
    notification.show();
  }
  else
  {
    alert( "Please request permissions first." );
  }
}

function demoTimerNotify() {
  if ( !demoCheck() ) return;
  if ( webkitNotifications.checkPermission() == 0 )
  {
    var iconImageUrl = "http://0.gravatar.com/avatar/25c07794aa15e4173b0f8b5c3f66c66b?s=64&#038;d=http://0.gravatar.com/avatar/ad516503a11cd5ca435acc9bb6523536%3Fs%3D32&#038;r=G";
    var title = "Andrew sent you another message";
    var subTitle = "This notification will disappear in 10 seconds.";

    var notification = webkitNotifications.createNotification( iconImageUrl, title, subTitle );
    notification.show();
    setTimeout( function() { notification.cancel() }, 10000 );
  }
  else
  {
    alert( "Please request permissions first." );
  }
}
//--></script></pre>
<p>I&#8217;ve seen a number of blog posts floating around today about GMail Desktop Notifications (<a href="http://downloadsquad.switched.com/2011/01/26/gmail-enables-html5-powered-desktop-notifications/?utm_source=feedburner&#038;utm_medium=feed&#038;utm_campaign=Feed%3A+weblogsinc%2Fdownloadsquad+%28Download+Squad%29&#038;utm_content=Google+Reader">here</a>, <a href="http://lifehacker.com/5744356/gmail-now-has-desktop-notifications-baked-in-for-chrome">here</a>, <a href="http://mashable.com/2011/01/27/gmail-desktop-notifications/">here</a>, <a href="http://www.engadget.com/2011/01/27/google-adds-html5-gmail-and-gtalk-notifications-for-the-desktop/">here</a> and <a href="http://googlesystem.blogspot.com/2011/01/gmail-desktop-notifications.html">here</a> &#8212; did I miss anyone?). I tried them out myself and they are very useful. Being a rich web applications developer I, of course, wanted to figure out how it works and how I could use it for my own apps. Here&#8217;s a quick overview of what I found.<br />
<span id="more-596"></span></p>
<p>There is a proposed web notification standard over at the W3C that Google submitted earlier this month (you can find it on the <a href="http://dev.w3.org/2006/webapi/WebNotifications/publish/Notifications.html">W3C site</a>) but from what I can tell, that draft isn&#8217;t implemented in any browsers (including Google Chrome!). But  you can get desktop notifications today without the need for any third-party browser extensions, if you&#8217;re using Google Chrome. You can find the documentation <a href="http://www.chromium.org/developers/design-documents/desktop-notifications/api-specification">over on the Chromium developer site</a>. The rest of this post is a collection of quick examples I put together for using notifications:</p>
<h3>Checking for permission</h3>
<p>It is pretty easy to check to see if the user has allowed notifications for your website. The first example displays an alert depending on the permission level.</p>
<pre class="brush: jscript; title: ; notranslate">
switch ( webkitNotifications.checkPermission() )
{
  case 0: // PERMISSION_ALLOWED
    alert( &quot;Permission: allowed&quot; );
    break;
  case 1: // PERMISSION_NOT_ALLOWED
    alert( &quot;Permission: not allowed&quot; );
    break;
  case 2: // PERMISSION_DENIED
    alert( &quot;Permission: denied&quot; );
    break;
}
</pre>
<p>Try it: <a href="javascript: demoCheckPermission()">Check Permission</a></p>
<p>Unless you skipped ahead and tried the next bit of code, the answer is &#8220;No&#8221; my site doesn&#8217;t have permission to display notifications.</p>
<h3>Requesting Permission</h3>
<p>So before we do anything we need to ask for permission.</p>
<p>This method will only work when responding to a user gesture. Which means you can call it as a direct response to an action taken by the user; but you can&#8217;t call it (for example) on the response to an Ajax function. So if you wanted to call it when your Ajax call returns or when a timer fires, you&#8217;re out of luck. You need to request permission before then.</p>
<pre class="brush: jscript; title: ; notranslate">
webkitNotifications.requestPermission();
</pre>
<p>Try it: <a href="javascript: demoRequestPermission()">Request Permission</a></p>
<h3>Creating and Showing Notification</h3>
<p>Notably, showing a standard browser alert dialog when permission is denied is a terrible user experience. Don&#8217;t do that! This is just for demo purposes.</p>
<pre class="brush: jscript; title: ; notranslate">
if ( webkitNotifications.checkPermission() == 0 )
{
  var iconImageUrl = &quot;http://www.example.com/foo.png&quot;;
  var title = &quot;Hello World&quot;;
  var subTitle = &quot;This is a sample desktop notification.&quot;

  var notification = webkitNotifications.createNotification( iconImageUrl, title, subTitle );
  notification.show();
}
else
{
  alert( &quot;Please request permissions first.&quot; );
}
</pre>
<p>Try it: <a href="javascript: demoNotify()">Show Notification</a></p>
<p>The new notification looks something like this (for those of you not using Chrome and want to see what I am talking about):</p>
<div id="attachment_620" class="wp-caption alignnone" style="width: 318px"><a href="http://andrewcurioso.com/wp-content/uploads/2011/01/Screen-shot-2011-01-27-at-11.30.06-AM.png"><img src="http://andrewcurioso.com/wp-content/uploads/2011/01/Screen-shot-2011-01-27-at-11.30.06-AM.png" alt="Andrew sent you a message" title="Example Google Chrome Notification" width="308" height="80" class="size-full wp-image-620" /></a><p class="wp-caption-text">Example Notification (Google Chrome on OS X)</p></div>
<h3>Creating and Showing an HTML Notification</h3>
<p>You can also create a notification by passing in a URL.</p>
<pre class="brush: jscript; title: ; notranslate">
if ( webkitNotifications.checkPermission() == 0 )
{
  var url = &quot;http://www.example.com/notification.html&quot;;
  var notification = webkitNotifications.createHTMLNotification( url );
  notification.show();
}
else
{
  alert( &quot;Please request permissions first.&quot; );
}
</pre>
<p>Try it: <a href="javascript: demoHtmlNotify()">Show Notification</a></p>
<p>At first this seems like a terrible idea. It could be yet another way to have annoying advertisements pop up on a site. But it&#8217;s not as bad as it sounds since the user has to explicitly allow the notifications and they can be turned off at any time.</p>
<h3>One Final Example</h3>
<p>Now, you probably don&#8217;t want the notification to pop up and stay there forever. So, you can auto-hide it using a timer.</p>
<pre class="brush: jscript; title: ; notranslate">
if ( webkitNotifications.checkPermission() == 0 )
{
  var iconImageUrl = &quot;http://www.example.com/foo.png&quot;;
  var title = &quot;Hello World&quot;;
  var subTitle = &quot;This is a sample desktop notification.&quot;

  var notification = webkitNotifications.createNotification( iconImageUrl, title, subTitle );
  notification.show();
  setTimeout( function() { notification.cancel() }, 10000 );
}
else
{
  alert( &quot;Please request permissions first.&quot; );
}
</pre>
<p>Try it: <a href="javascript: demoTimerNotify()">Show Notification</a></p>
<h3>Wrapping it Up</h3>
<p>I hope someone found this useful. If you do anything cool with this library please let me know in the comments.</p>
<p class="pitfall">Note: this is an experimental API that only works in Google Chrome right now. The API may change at any time and may be different when other browsers decide to implement similar functionality. Use with caution. Always check to make sure <code>window.webkitNotifications !== undefined</code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://andrewcurioso.com/2011/01/ria-desktop-notifications-in-google-chrome/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>My 2011 New Year&#8217;s resolutions</title>
		<link>http://andrewcurioso.com/2011/01/my-2011-new-years-resolutions/</link>
		<comments>http://andrewcurioso.com/2011/01/my-2011-new-years-resolutions/#comments</comments>
		<pubDate>Mon, 17 Jan 2011 15:47:24 +0000</pubDate>
		<dc:creator>Andrew Curioso</dc:creator>
				<category><![CDATA[Personal]]></category>

		<guid isPermaLink="false">http://andrewcurioso.com/?p=586</guid>
		<description><![CDATA[I haven&#8217;t written a blog posts in a while so it figured a good start might be to make some resolutions for myself in the new year (yes, I know that January is almost over). Here are few things I want to improve: First, and I&#8217;ve been saying this for a while, I need to [...]]]></description>
			<content:encoded><![CDATA[<p>I haven&#8217;t written a blog posts in a while so it figured a good start might be to make some resolutions for myself in the new year (yes, I know that January is almost over).</p>
<p>Here are few things I want to improve:<br />
<span id="more-586"></span><br />
First, and I&#8217;ve been saying this for a while, I need to <strong>start blogging more</strong>. This post is a okay start but I want to finish my initiative that I start back in December. Which is to to break the site up into code in business and to post in each of those categories at least once a month. Once I get there, I can see where it goes.</p>
<p>Second, I&#8217;m going to <strong>start replying to more e-mails</strong>. This may seem like a no-brainer but I haven&#8217;t been in the habit of replying to e-mails that aren&#8217;t urgent or work related. So a lot of e-mails and the going unanswered. I want to change that.</p>
<p>Third, I want to <strong>participate more in the open source world</strong>. I work for start up so it&#8217;s difficult to find any time to work on open-source projects, but I imagine I can find a little time here and there and I want to all get a bit more involved with the community. I believe open source is fundamental to innovation and I think I can make some valuable contributions.</p>
<p>Fourth, and this is really my only non-tech related goal, I want to <strong>be more active in my life</strong>. Being a software engineer it&#8217;s sometimes easy to get into a rut where you&#8217;re just sitting at a desk 12+ hours a day staring at a computer screen. It&#8217;s clearly not the most healthy thing in the world. So my final resolution is to get out and be more active on both in the community and also in a more traditional sense (exercising, eating right, etc.).</p>
<p>Usually don&#8217;t like to post about my personal life but I want to get this out there for everybody to see. Maybe it will provide a bit of motivation. I know that some of you out there will start nagging me if I fall behind (thank you for that). And finally I wish you all the absolute best in this new year and with everything you do.</p>
]]></content:encoded>
			<wfw:commentRss>http://andrewcurioso.com/2011/01/my-2011-new-years-resolutions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Error handling stack in PHP 5.3+</title>
		<link>http://andrewcurioso.com/2010/10/error-handeling-stack-in-php-5-3/</link>
		<comments>http://andrewcurioso.com/2010/10/error-handeling-stack-in-php-5-3/#comments</comments>
		<pubDate>Wed, 13 Oct 2010 15:49:49 +0000</pubDate>
		<dc:creator>Andrew Curioso</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://andrewcurioso.com/?p=518</guid>
		<description><![CDATA[Update: this article is mentioned in a few places as a practical example of using closures. Some languages pass variables into a closure automatically. In PHP it needs to be done explicitly using the use keyword. See line #6 of the code example. I was inspired by a question that I was asked on Twitter [...]]]></description>
			<content:encoded><![CDATA[<p class="update"><strong>Update:</strong> this article is mentioned in a few places as a practical example of using <strong>closures</strong>.<br />
Some languages pass variables into a closure automatically. In PHP it needs to be done explicitly using the <strong>use</strong> keyword. See line #6 of the code example.</p>
<p>I was inspired by a question that I was asked on Twitter to write a quick code snippet.</p>
<p>As you may know, set_error_handler can be used to set a custom error handler in PHP. It will catch any errors that happen in the script (with a few notable exceptions). If the function returns false then error handling resumes as normal; otherwise it is assumed that the custom handler took care of things. The problem is that you can only have one error handler active at one time. The purpose of this code is to provide a error handeling stack for PHP.</p>
<p>Using this code you can have more than one error handler while taking advantage of the set_error_handler function.<br />
<span id="more-518"></span><br />
Because this example uses closures, it will only work in PHP 5.3 or newer.</p>
<pre class="brush: php; title: ; notranslate">
function push_error_handler( $error_handler, $error_types = 32767 )
{
  $old_callback = null;

  $callback = function( $errno, $errstr, $errfile, $errline, $errcontext )
  use ( &amp;$old_callback, $error_handler )
  {
    $result = call_user_func($error_handler, $errno , $errstr, $errfile, $errline, $errcontext);

    if ( $result === false &amp;&amp; $old_callback != null )
      return call_user_func( $old_callback, $errno , $errstr, $errfile, $errline, $errcontext );

    return $result;
  };

  $old_callback = set_error_handler($callback, $error_types);
}
</pre>
<p>Let&#8217;s see it in action:</p>
<pre class="brush: php; title: ; notranslate">
function test1( $a, $b, $c, $d, $e ) { echo &quot;Test 1 -- &quot;; return false; }
function test2( $a, $b, $c, $d, $e ) { echo &quot;Test 2 -- &quot;; return false; }
function test3( $a, $b, $c, $d, $e ) { echo &quot;Test 3 -- &quot;; return false; }
function test4( $a, $b, $c, $d, $e ) { echo &quot;Test 4 -- &quot;; return false; }

push_error_handler( 'test1' );
push_error_handler( 'test2' );
push_error_handler( 'test3' );
push_error_handler( 'test4' );

trigger_error('testing');
</pre>
<p>The output is:</p>
<pre class="brush: plain; title: ; notranslate">
Test 4 -- Test 3 -- Test 2 -- Test 1 --
Notice: testing in /Users/andrew/recursive_error_handler.php on line 32
</pre>
<p>It is worth a closer look. First we initialize a variable that will be needed by the closure later on. Then we define the closure (which will be our actual error handling function) and register it as the error handler. The function set_error_handler returns the old handler which we then assign to the variable that we created earlier. We also return the old handler to keep compatibility with the normal set_error_handler.</p>
<p>The closure itself calls the new error handler. If the handler returned false (resume error handeling) then we call the previous error handler (if there was one). We also make sure to pass the error code and the old callback function into the closure. It is important that the old callback is passed by reference (note the &#8220;&#038;&#8221;).</p>
<p>If you want to learn some more, here are some handy links:<br />
PHP Manual for <a href="http://us2.php.net/manual/en/function.set-error-handler.php">set_error_handler</a> and <a href="http://php.net/manual/en/functions.anonymous.php">anonymous functions and closures</a>.<br />
My book, <a href="http://www.amazon.com/gp/product/0470563125?ie=UTF8&#038;tag=365note-20&#038;linkCode=as2&#038;camp=1789&#038;creative=390957&#038;creativeASIN=0470563125">Expert PHP and MySQL</a><img src="http://www.assoc-amazon.com/e/ir?t=365note-20&#038;l=as2&#038;o=1&#038;a=0470563125" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />, also talks about closures in depth starting on page 78.</p>
<p class="pitfall">Note: this method only works if almost all the error handlers in the application use this or a similar method. Otherwise the chain will be broken. I say &#8220;almost&#8221; because the first registered error handler doesn&#8217;t have to worry about calling the previous handler since there isn&#8217;t any at that point.</p>
]]></content:encoded>
			<wfw:commentRss>http://andrewcurioso.com/2010/10/error-handeling-stack-in-php-5-3/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Welcome CakeFest 2010 Attendees</title>
		<link>http://andrewcurioso.com/2010/09/welcome-cakefest-2010-attendees/</link>
		<comments>http://andrewcurioso.com/2010/09/welcome-cakefest-2010-attendees/#comments</comments>
		<pubDate>Sat, 04 Sep 2010 12:37:31 +0000</pubDate>
		<dc:creator>Andrew Curioso</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://andrewcurioso.com/?p=461</guid>
		<description><![CDATA[I noticed a spike in my traffic which can only mean one thing: welcome, CakeFest attendees, to my home on the web! When conference day two roles around you&#8217;ll be able to find all my presentation notes here and I will be uploading the slides as well. As you may know, I will be talking [...]]]></description>
			<content:encoded><![CDATA[<p>I noticed a spike in my traffic which can only mean one thing: welcome, CakeFest attendees, to my home on the web!</p>
<p>When conference day two roles around you&#8217;ll be able to find all my presentation notes <a href="http://andrewcurioso.com/2010/06/cakefest-2010/">here</a> and I will be uploading the slides as well.</p>
<p>As you may know, I will be talking on API Development with CakePHP. It is a complex topic so my presentation won&#8217;t be the end of it, I will be adding additional information over time. So I hope that you <a href="http://andrewcurioso.com/feed/">subscribe to me via RSS</a>.</p>
<p>Happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://andrewcurioso.com/2010/09/welcome-cakefest-2010-attendees/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Authentication vs. Authorization</title>
		<link>http://andrewcurioso.com/2010/07/authentication-vs-authorization/</link>
		<comments>http://andrewcurioso.com/2010/07/authentication-vs-authorization/#comments</comments>
		<pubDate>Wed, 14 Jul 2010 19:03:40 +0000</pubDate>
		<dc:creator>Andrew Curioso</dc:creator>
				<category><![CDATA[Security]]></category>
		<category><![CDATA[curl]]></category>
		<category><![CDATA[hacking]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://andrewcurioso.com/?p=402</guid>
		<description><![CDATA[This seems like a no-brain-er but I have seen it more times than I can count and I have seen it happen to some very experienced developers. Put simply: authentication is not enough; you need to make sure that the authenticated user is actually authorized to perform an action. It is one thing to know [...]]]></description>
			<content:encoded><![CDATA[<p>This seems like a no-brain-er but I have seen it more times than I can count and I have seen it happen to some very experienced developers. Put simply: <strong>authentication</strong> is not enough; you need to make sure that the authenticated user is actually <strong>authorized</strong> to perform an action. It is one thing to know who a user is and an entirely different &#8212; though equally important &#8212; thing to know what a user is allowed to do.</p>
<p>This article covers the concepts of authentication and authorization.</p>
<p><span id="more-402"></span></p>
<p>Authentication is knowing who the logged in user is. Authorization is knowing what the user can and can&#8217;t do and can be as easy as checking that the user ID in the database matches the user ID of the authenticated user. It can also be as complex  as Access Control Lists, social graphs, and multi-moderator systems. Either way it needs to be taken care of. Very few things are more devastating than when a malicious user finds that all you have to do to edit another user&#8217;s data is to change the value of a POST variable or all you need to do to access someone&#8217;s private photos is to change a URL. Do either of those two cases sound familiar?</p>
<h2>Thinking like a hacker</h2>
<blockquote><p>
If I were to try to exploit this feature: how would I go about it?<br />
<span class="citation">you, every time you write code (hopefully)</span>
</p></blockquote>
<p>Let&#8217;s start by looking at a imaginary site that makes an Ajax request to delete a resource via a RESTful API. The HTTP request probably looks a bit like this:</p>
<pre class="brush: plain; title: ; notranslate">
POST /resources/1234.json HTTP/1.1
Host: www.example.com
Content-Length: 14

_method=DELETE
</pre>
<p>Now, make the assumption that you can find the ID of any resource on the system. This could be because it is exposed in a &#8220;view&#8221; URL or it could be that it is returned in an API call for search. Either way, assume that if it exists a hacker can find it either by design or through flaws in the code. Never assume primary keys are a secret. The next step is to find an ID of a resource not owned by the hacker (in this example: 5678) and to go the command line (assuming cURL is installed on your system):</p>
<pre class="brush: plain; title: ; notranslate">
curl -d &quot;_method=delete&quot; http://www.example.com/resources/5678.json
</pre>
<p>Curl doesn&#8217;t share cookies with the web browser so if that call succeeded and record 5678 was actually deleted then the application is not checking to see if the user is <strong>authenticated</strong>. There is no need to go any further, you&#8217;ve already found a devastating exploit. If this is your application (I hope that you aren&#8217;t using this article to try to hack other people&#8217;s apps!) it is time to go back to the code, add a check to make sure that the user is logged in. Then come back here to read on.</p>
<p>If the call didn&#8217;t work then it is time to try to delete the resource as an authenticated (but hypothetically not authorized) user:</p>
<pre class="brush: plain; title: ; notranslate">
curl -d &quot;username=you&amp;password=abcdefg&quot; -c &quot;cookies.txt&quot; http://www.example.com/login/
curl -d &quot;_method=delete&quot; -b &quot;cookies.txt&quot; http://www.example.com/resources/5678.json
</pre>
<p>The first line authenticates the user and stores the cookies. The second line tries the delete method again with the new cookies. Make sure to replace all the appropriate variables and URLs in all of these examples. If all went <del>well</del> bad the resource 5678 should now be deleted. If that happened then the application needs to check for <strong>authorization</strong> as well as authentication.</p>
<p>The same concepts can be applied to viewing, editing, and creating resources. This article uses cURL but there are numerous other ways of spoofing Ajax and API requests, including injecting Javascript into the browser and writing a PHP / Perl / Ruby / Python / etc. script to do it.</p>
<p class="pitfall">One thing to watch out for is any request that takes the user ID as a parameter. It should raise a red flag. Whenever possible, get the user ID from the currently authenticated user. I once saw a password vault web application that returned the entire password list from a SOAP call given only the user ID. Just so you are sufficiently mortified, I&#8217;ll rephrase it: I could enter in any user&#8217;s ID and get back a list of passwords for other sites on the Internet (including Google). Don&#8217;t let that happen to you!</p>
<h2>Taking care of business</h2>
<p>Addressing the problem takes as much thought and planning then actually technical know-how. Imagine a user for each role (resource owner, administrator, moderator, customer support, friend of the user &#8212; if you are a social network &#8212; etc.) then ask three questions:</p>
<ol>
<li>User X can/can&#8217;t view resource Y because&#8230;</li>
<li>User X can/can&#8217;t edit resource Y because&#8230;</li>
<li>User X can/can&#8217;t delete resource Y because&#8230;</li>
</ol>
<p>Then for each of those, check to make sure the code reinforces that statement. It is also a good idea to give these stories to the testers and have them try to break your code. And remember: the authentication system tells you WHO the user is and authorization system tells you WHAT actions the user can perform.</p>
<p>How complex a system you need for authorization depends on your application. It can range from one-off code to full-featured generic systems that can be used for any type of resource imaginable. Social networks are the most complicated of the bunch because authorization often depends on a personal relationship with the user requesting access to the resource. The simplest form of authentication is:</p>
<pre class="brush: php; title: ; notranslate">
if ( $user-&gt;id != $resource-&gt;owner_id )
  throw new Exception(&quot;Access denied&quot;);
</pre>
<p>Or if your application is a social network and you give friend&#8217;s access to resources:</p>
<pre class="brush: php; title: ; notranslate">
if ( $user-&gt;id != $resource-&gt;owner_id &amp;&amp; !$user-&gt;isFriendsWith($resource-&gt;owner_id) )
  throw new Exception(&quot;Access denied&quot;);
</pre>
<p>For a more robust system you&#8217;ll probably want to implement an Access Control List (ACL). An ACL at its core is just a mapping of users to resources. For example: Joe has view, edit, and delete access to resource 1234.</p>
<p>More advanced access control lists also have groups (called &#8220;roles&#8221;) and they can cascade. Roles introduce some ambiguity, and multiple entries in the list may govern the same action. If that happens, the most specific one is taken. For example, editing a resource may be governed by the rules:</p>
<ul>
<li>&#8220;Joe&#8221; is in the group &#8220;Basic Users&#8221; and &#8220;Basic Users&#8221; explicitly can NOT edit resources of type &#8220;forum post&#8221;
	</li>
<li>&#8220;Joe&#8221; CAN edit resources of type &#8220;forum post&#8221; with ID &#8220;1234&#8243;
</li>
</ul>
<p>Since Joe has edit rights to the forum post with an ID of 1234 it doesn&#8217;t matter that the role Joe plays (a &#8220;Basic User&#8221;) cannot edit any forum posts.  There are numerous articles on implementing an ACL in a PHP application and many frameworks have built-in classes for ACL.</p>
<h2>Summary</h2>
<p>When developing web applications (or any application for that matter): always be cognizant of authentication and authorization. Remember, authentication answers the question of WHO and authorization answers the question of WHAT. The application must always know the answer to both of those questions and be able to deny or allow certain actions based on those answers. It might be useful for newer developers to to actually put themselves in the shoes of a hacker and attempt to find exploits for their own website. Eventually, it will become second nature.</p>
]]></content:encoded>
			<wfw:commentRss>http://andrewcurioso.com/2010/07/authentication-vs-authorization/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CakeFest 2010 &#8211; Chicago, IL</title>
		<link>http://andrewcurioso.com/2010/06/cakefest-2010/</link>
		<comments>http://andrewcurioso.com/2010/06/cakefest-2010/#comments</comments>
		<pubDate>Thu, 24 Jun 2010 15:39:28 +0000</pubDate>
		<dc:creator>Andrew Curioso</dc:creator>
				<category><![CDATA[Portfolio]]></category>

		<guid isPermaLink="false">http://andrewcurioso.com/?p=333</guid>
		<description><![CDATA[CakeFest is an annual gathering of CakePHP developers. The 2010 conference was held in Chicago, IL on September 2nd and 5th. I presented a talk on API Development. &#160; Andrew CuriosoAndrew Curioso Reviewspowered by Speaker Wiki]]></description>
			<content:encoded><![CDATA[<p>CakeFest is an annual gathering of CakePHP developers. The 2010 conference was held in Chicago, IL on September 2nd and 5th.</p>
<p>I  presented a talk on API Development.</p>
<p><span id="more-333"></span></p>
<div style="width:425px" id="__ss_5133812"><object id="__sse5133812" width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=cakefest-100905125231-phpapp02&#038;stripped_title=cakefest-2010-api-development" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed name="__sse5133812" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=cakefest-100905125231-phpapp02&#038;stripped_title=cakefest-2010-api-development" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed></object><br />
<br />&nbsp;</div>
<p>
<a href="http://tv.cakephp.org/video/CakeFoundation/2010/12/24/andrew_curioso_-_developing_an_api"><img src="http://andrewcurioso.com/wp-content/uploads/2010/06/cakefest-video.jpg" alt="Play Video" title="cakefest-video" width="566" height="350" class="alignleft size-full wp-image-643" /></a><br style="clear: both" /></p>
<p><div id='sw_1'>
<div id='sw_content_1' style="float: right"><a href='http://speakerwiki.org/speakers/Andrew_Curioso'>Andrew Curioso</a><br /><a href='http://speakerwiki.org/speakers/Andrew_Curioso/reviews' alt='Andrew Curioso Reviews'>Andrew Curioso Reviews</a><br />powered by <a href='http://speakerwiki.org'>Speaker Wiki</a></div>
</div>
<p><script type='text/javascript'>document.getElementById('sw_content_1').style.visibility = 'hidden';window.onload = function() {var s = document.createElement('script');s.type = 'text/javascript';s.async = true;s.src = 'http://api.speakerwiki.org/speakers/Andrew_Curioso/lanyard/embed?v=1';var x = document.getElementsByTagName('script')[0];x.parentNode.insertBefore(s, x);}</script></p>
]]></content:encoded>
			<wfw:commentRss>http://andrewcurioso.com/2010/06/cakefest-2010/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Detecting file size overflow in PHP</title>
		<link>http://andrewcurioso.com/2010/06/detecting-file-size-overflow-in-php/</link>
		<comments>http://andrewcurioso.com/2010/06/detecting-file-size-overflow-in-php/#comments</comments>
		<pubDate>Thu, 10 Jun 2010 03:55:06 +0000</pubDate>
		<dc:creator>Andrew Curioso</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://andrewcurioso.com/?p=232</guid>
		<description><![CDATA[One of the things that separates a good web application from a great one is how gracefully they handle failures. One of the often overlooked cases is when a user attempts to upload a file that exceeds the set PHP upload file size. This article shows how to detect when the user tries to upload [...]]]></description>
			<content:encoded><![CDATA[<p>One of the things that separates a good web application from a great one is how gracefully they handle failures. One of the often overlooked cases is when a user attempts to upload a file that exceeds the set PHP upload file size. This article shows how to detect when the user tries to upload a file that is too large and display an appropriate message.<br />
<span id="more-232"></span><br />
This article assumes that you have already set upload_max_filesize, post_max_size, and memory_limit in your php.ini file to appropriate values. It also assumes that you already have a working file upload form. There are plenty of tutorials out there already to get you started. </p>
<p>If you can, you may want to set post_max_size to a low value (say &#8220;1M&#8221;) to make testing easier. </p>
<p>First test to see how your script behaves. Try uploading a file that is larger than post_max_size. If you do you will get a message like this in your error log:</p>
<pre class="brush: plain; title: ; notranslate">
[09-Jun-2010 19:28:01] PHP Warning:  POST Content-Length of 30980857 bytes exceeds the limit of 2097152 bytes in Unknown on line 0
</pre>
<p>If you&#8217;re not careful this can lead to unexpected behavior in your application. The end result can range from silent failure all the way to lost customers.</p>
<h2>Solving the problem</h2>
<p>The PHP documentation provides a hack to solve this problem:</p>
<blockquote><p>If the size of post data is greater than post_max_size, the $_POST and $_FILES  superglobals  are empty. This can be tracked in various ways, e.g. by passing the $_GET variable to the script processing the data, i.e. &lt;form action=&#8221;edit.php?processed=1&#8243;&gt;, and then checking if $_GET['processed'] is set.<br />
<a href="http://php.net/manual/en/ini.core.php" class="citation">Source: PHP manual</a></p></blockquote>
<p>To be clear, it is suggesting that you pass a value in the query string along with your form. If the value is in the $_GET superglobal and both $_FILE and $_POST are empty then the maximum upload size is exceeded. There are two problems with this approach: it adds extra complexity on the front-end and it can potential give a false positive.</p>
<p>Extra complexity on the front-end means extra documentation and more room for mistakes. And if there is a mistake it may not be caught for a long time (does your QA team routinely upload large files?).  In this case we already have all the data that we need to determine if the maximum file size was exceeded without adding extra complexity and headache for developers.</p>
<p>We know what type of request is being processed, we have the $_POST and $_FILES arrays, and we have the content length as it was passed to the HTTP server from the client.  From that we get this code:</p>
<pre class="brush: php; title: ; notranslate">
if ( $_SERVER['REQUEST_METHOD'] == 'POST' &amp;&amp; empty($_POST) &amp;&amp;
     empty($_FILES) &amp;&amp; $_SERVER['CONTENT_LENGTH'] &gt; 0 )
{
  $displayMaxSize = ini_get('post_max_size');

  switch ( substr($displayMaxSize,-1) )
  {
    case 'G':
      $displayMaxSize = $displayMaxSize * 1024;
    case 'M':
      $displayMaxSize = $displayMaxSize * 1024;
    case 'K':
       $displayMaxSize = $displayMaxSize * 1024;
  }

  $error = 'Posted data is too large. '.
           $_SERVER[CONTENT_LENGTH].
           ' bytes exceeds the maximum size of '.
           $displayMaxSize.' bytes.&quot;;
}
</pre>
<p>The important thing to notice is the &#8220;if&#8221; statement on lines one and two. The example code just sets an error string. Production code might display a message to the user, execute some Javascript (for asynchronous uploads), or pass back a XML or Json object for Flash clients.</p>
<p>I&#8217;ve tested this code with Apache as both a module and as CGI. As far as I know it should work fine with IIS as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://andrewcurioso.com/2010/06/detecting-file-size-overflow-in-php/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

