<?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; PHP</title>
	<atom:link href="http://andrewcurioso.com/category/php/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>3</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>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>4</slash:comments>
		</item>
		<item>
		<title>5 things about PHP 5.3 that make me smile</title>
		<link>http://andrewcurioso.com/2009/06/5-things-about-php-53-that-make-me-smile/</link>
		<comments>http://andrewcurioso.com/2009/06/5-things-about-php-53-that-make-me-smile/#comments</comments>
		<pubDate>Wed, 01 Jul 2009 03:41:08 +0000</pubDate>
		<dc:creator>Andrew Curioso</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[early adopters]]></category>

		<guid isPermaLink="false">http://andrewcurioso.com/?p=89</guid>
		<description><![CDATA[Rest assured. Soon I will be writing &#8220;Things about PHP 5.3 that make me cringe&#8221; but for now I sing the praises of the latest release of PHP that that came out today. I&#8217;ve been playing with the new release for months and there are indeed many good things about it and many of them [...]]]></description>
			<content:encoded><![CDATA[<p>Rest assured. Soon I will be writing &#8220;Things about PHP 5.3 that make me cringe&#8221; but for now I sing the praises of the latest release of PHP that that came out today. I&#8217;ve been playing with the new release for months and there are indeed many good things about it and many of them have been a long time coming.</p>
<p>The other day I was reading the release notes and I couldn&#8217;t help but smile.<br />
<span id="more-89"></span></p>
<h3>1. New native MySQL driver</p>
<p>I&#8217;m saving the best for last. So bear with me. Lets get through the small grins before we get to the big toothy ones (or you can read ahead&#8230; you&#8217;re choice). PHP 5.3 ships with a new MySQL driver called mysqlnd. A database driver is responsible for making the actually connection from PHP to MySQL. The previous MySQL driver had some flaws. For one, it was license in a way that was not compatible with the PHP license. The new <em>MySQL Native Driver</em> has a more amicable license (which is big in the open source world). It also adds some experimental functionality including improved persistent connections. There is also a down side but that is for another post.</p>
</h3>
<h3>2. Host specific PHP INI configurations</h3>
<p>I previously worked on a hosted CMS and web publishing tool that had dozens of virtual hosts but only one php.ini. The new functionality allows to section off your PHP configuration to have a different configuration for every host or file path. I haven&#8217;t tried this one yet so I&#8217;m not sure how well it works. Try it out for yourself. There is a comment on <a href="http://www.php.net/">PHP.net</a> right now saying that it only works for CGI PHP and not for the CLI implementation.<br />
<span class="syntaxhighlighterContainer">
<pre class="brush: plain; title: ; notranslate">
[HOST=example.com]
error_reporting = E_ALL
display_errors = On
</pre>
<p></span><br />
Example from the PHP documentation.</p>
<h3>3. Shortcut ternary operator</h3>
<p>I had never considered this before. However, this saves a lot of time for rather repetitive code. Consider these three identical code snipits.<br />
<span class="syntaxhighlighterContainer">
<pre class="brush: php; title: ; notranslate">
&lt;?php
if ( $foo ) $x = $foo;
else $x = $bar;

$x = ( $foo ? $foo : $bar );
$x = ( $foo ?: $bar );
?&gt;
</pre>
<p></span></p>
<p>The third method is the new shortcut. It reads simply: &#8220;if foo than foo else bar.&#8221; I am still waiting for the first time for this to be useful. The biggest issue I see is that in the above example $foo cannot legitimately be anything that evaluates to false. As a result it is best used for variables that should be non-empty strings or non-zero numbers.</p>
<h3>4. Date math</h3>
<p>The DateTime class now has several new methods in it for dealing with date arithmetic. It puts an end to manually converting to timestamps and back to dates again. It works very simply:<br />
<span class="syntaxhighlighterContainer">
<pre class="brush: php; title: ; notranslate">
&lt;?php
$date = new DateTime('2009-06-30 09:00:00');
$date-&gt;sub('P5D'); // Subtract five days
echo $data-&gt;diff( new DateTime() )-&gt;format('%d').' days ago';
?&gt;
</pre>
<p></span><br />
The new DateTime methods and the new DateInterval class (returned from and passed to math functions) aren&#8217;t very well documented because they are so new.<br />
It is worth noting that the format methods are different in the two classes. Intervals require a percentage (%) in front of placeholders. Watch out for that.</p>
<h3>5. Closures</h3>
<p>Closures are one of the best parts of PHP 5.3. At first I wasn&#8217;t very excited about them. I use closures constantly in Javascript but in a stateless HTTP request situation they appear less useful. But then I got into it. They are improved methods of dealing with lambda-functions. In other words, they are functions that are nameless and can be assigned to variables. In actuality they are classes.<br />
<span class="syntaxhighlighterContainer">
<pre class="brush: php; title: ; notranslate">
&lt;?phpi
$y = 10;
$x = function($number) use ( &amp;$y ) {
  return $number * $y;
};
$y = 100;
echo $x(8); // Output: 800
?&gt;
</pre>
<p></span><br />
This is the point at which a lot of PHP programmers would pause. Did I say they are classes? Since when can you call a class like it was a function? Since PHP 5.3 you can! . You do it by defining the &#8220;_invoke&#8221; magic method. Like so:<br />
<span class="syntaxhighlighterContainer">
<pre class="brush: php; title: ; notranslate">
&lt;?php
class testInvoke {
  public function __invoke( $x ) { echo &quot;Hello $x&quot;; }
};
$x = new TestInvoke();
echo $x('world'); // outputs &quot;Hello World&quot;
?&gt;
</pre>
<p></span><br />
This is by far one of the coolest new features in PHP 5.3. It opens a whole new world of possibilities for clean / manageable code.</p>
<h3>Bonus Things</h3>
<h4>5.1. New magic method for matching calls to static methods</h4>
<p>For a while now we have been able to define the magic method &#8220;__call&#8221; in our classes that will be executed if you try to call a method in a class instance that does not exist. Now the &#8220;__callStatic&#8221; method does the same thing only for methods of static classes.</p>
<h4>5.2. Late static binding</h4>
<p>Late static binding is a long time coming. In fact, this has tripped me up in several projects. In simplest terms late binding is waiting to determine what object a method or member variable belongs to until it is called. Late static binding in PHP, as its name indicates, applies this concept to static methods and members variables in PHP. The PHP.net website bests describes in on the <a href="http://us.php.net/lsb">manual page for late static binding</a>.</p>
<h4>5.3. E_DEPRECATED</h4>
<p>Here is a tip for everyone: if you are developing open source PHP software you should develop it in E_STRICT mode. This new E_DEPRECATED flag is actually part of E_ALL which sends a strong message that you shouldn&#8217;t be using these depreciated functions. I am a huge fan of anything that helps us write better code.</p>
<p>I hope everyone got through this post just fine. It is a long one. Leave comments (the comment section is OpenID enabled).</p>
]]></content:encoded>
			<wfw:commentRss>http://andrewcurioso.com/2009/06/5-things-about-php-53-that-make-me-smile/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

