<?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/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://andrewcurioso.com</link>
	<description>Tech, Social Media, PHP, Opinions</description>
	<lastBuildDate>Sat, 04 Sep 2010 12:37:31 +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>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;">
[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;">
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>2</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</h2>
<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 mysqld. 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>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;">
[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;">
&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;">
&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;">
&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;">
&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>1</slash:comments>
		</item>
	</channel>
</rss>
