<?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>Untitled &#187; php</title>
	<atom:link href="http://ammonlauritzen.com/blog/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://ammonlauritzen.com/blog</link>
	<description>and still for good reason.</description>
	<lastBuildDate>Wed, 05 May 2010 18:43:20 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>dead simple traditional style rotation</title>
		<link>http://ammonlauritzen.com/blog/2010/02/05/dead-simple-traditional-style-rotation/</link>
		<comments>http://ammonlauritzen.com/blog/2010/02/05/dead-simple-traditional-style-rotation/#comments</comments>
		<pubDate>Fri, 05 Feb 2010 17:51:26 +0000</pubDate>
		<dc:creator>Ammon</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[sysadmin]]></category>
		<category><![CDATA[logfiles]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://ammonlauritzen.com/blog/?p=1105</guid>
		<description><![CDATA[In response to my two-step rotation post earlier this week, I figure I may as well share the logic I use for a more traditional logfile rotation scheme.
I think this is as simple as I can possibly make it:

&#60;?
define( 'MAX_COPIES', 3 );
$back_fname = &#34;/path/to/log/file/abc.log&#34;;

function trace( $msg ) {
    echo &#34;- $msg\n&#34;;
}

exec( &#34;ls [...]]]></description>
			<content:encoded><![CDATA[<p>In response to <a href='http://ammonlauritzen.com/blog/2010/02/03/simple-two-step-logfile-rotation/'>my two-step rotation post</a> earlier this week, I figure I may as well share the logic I use for a more traditional logfile rotation scheme.</p>
<p>I think this is as simple as I can possibly make it:</p>
<pre class="brush: php;">
&lt;?
define( 'MAX_COPIES', 3 );
$back_fname = &quot;/path/to/log/file/abc.log&quot;;

function trace( $msg ) {
    echo &quot;- $msg\n&quot;;
}

exec( &quot;ls -r ${back_fname}*&quot;, $copies, $succ );
while( count($copies) &gt;= MAX_COPIES ) {
    $fname = array_shift($copies);
    trace( &quot;deleting &quot;.$fname );
}
$next = count($copies);
while( $fname = array_shift($copies) ) {
    --$next;
    trace( &quot;rotating $fname -&gt; $next&quot; );
    rename( $fname, &quot;$back_fname.$next&quot; );
}

trace( &quot;creating $back_fname&quot; );
touch( $back_fname );
?&gt;
</pre>
<p>A sample series of executions might look like this:</p>
<pre class="brush: plain;">
ammon@wernstrom:/path/to/log/file$ touch abc.log
ammon@wernstrom:/path/to/log/file$ php rotate.php
- rotating /path/to/log/file/abc.log -&gt; 0
- creating /path/to/log/file/abc.log
ammon@wernstrom:/path/to/log/file$ php rotate.php
- rotating /path/to/log/file/abc.log.0 -&gt; 1
- rotating /path/to/log/file/abc.log -&gt; 0
- creating /path/to/log/file/abc.log
ammon@wernstrom:/path/to/log/file$ php rotate.php
- rotating /path/to/log/file/abc.log.1 -&gt; 2
- rotating /path/to/log/file/abc.log.0 -&gt; 1
- rotating /path/to/log/file/abc.log -&gt; 0
- creating /path/to/log/file/abc.log
ammon@wernstrom:/path/to/log/file$ php rotate.php
- deleting /path/to/log/file/abc.log.2
- rotating /path/to/log/file/abc.log.1 -&gt; 2
- rotating /path/to/log/file/abc.log.0 -&gt; 1
- rotating /path/to/log/file/abc.log -&gt; 0
- creating /path/to/log/file/abc.log
</pre>
<p>This doesn&#8217;t have any failsafes, doesn&#8217;t compress anything, depends on an external call to &#8216;ls&#8217;, and it actually deletes old files in stead of overwriting them&#8230; but it is the shortest, simplest method I&#8217;ve come up with to get the job done.</p>
<p>If I feel like making this a full-fledged series, I might actually post a more thorough implementation later <img src='http://ammonlauritzen.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://ammonlauritzen.com/blog/2010/02/05/dead-simple-traditional-style-rotation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>simple two-step logfile rotation</title>
		<link>http://ammonlauritzen.com/blog/2010/02/03/simple-two-step-logfile-rotation/</link>
		<comments>http://ammonlauritzen.com/blog/2010/02/03/simple-two-step-logfile-rotation/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 19:23:08 +0000</pubDate>
		<dc:creator>Ammon</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[sysadmin]]></category>
		<category><![CDATA[logfiles]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://ammonlauritzen.com/blog/?p=1103</guid>
		<description><![CDATA[This is the result of 10 minutes of pounding on the keyboard after yet another disappointing experience with trying to get logrotate to do something vaguely more flexible.
This simple script scans all normal files in a log directory, and if they are older than a certain cutoff, moves them into a holding directory for old [...]]]></description>
			<content:encoded><![CDATA[<p>This is the result of 10 minutes of pounding on the keyboard after yet another disappointing experience with trying to get logrotate to do something vaguely more flexible.</p>
<p>This simple script scans all normal files in a log directory, and if they are older than a certain cutoff, moves them into a holding directory for old logs. Future passes will check files in the old directory for another age setting and will delete them. That&#8217;s all there is to it.</p>
<p>Configure your cutoffs, directories of interest, and optionally plug in a better logging mechanism and you&#8217;re set. (Oh, and change the #! if necessary, of course).</p>
<pre class="brush: php;">
#!/usr/bin/php
&lt;?
$cutoff_rotate = &quot;3 days&quot;;
$cutoff_delete = &quot;7 days&quot;;
$dir_log = &quot;/logs&quot;;
$dir_old = &quot;/logs.old&quot;;

function trace( $msg, $debug = FALSE ) {
	// appropriate logging mechanism can be plugged in here
	echo &quot;[] $msg\n&quot;;
}

// scan old files for deletion
if( is_dir($dir_old) ) {
	$dh = opendir( $dir_old );
	if( $dh !== FALSE ) {
		chdir( $dir_old );
		trace( &quot;scanning $dir_old for logs more than $cutoff_delete old&quot; );
		$cutoff = strtotime( &quot;-$cutoff_delete&quot; );
		trace( &quot;cutoff is &quot;.date('r',$cutoff) );
		while( ($file = readdir($dh)) !== FALSE ) {
			if( is_dir($file) ) {
				trace( &quot;skipping $file&quot;, true );
				continue;
			} else {
				$ts = filemtime($file);
				if( $ts &lt; $cutoff ) {
					trace( &quot;deleting $file, &quot;.date('r',$ts) );
					$succ = @unlink($file);
					if( !$succ )
						trace( &quot;failed to unlink $file!&quot; );
				} else {
					trace( &quot;ignoring $file, &quot;.date('r',$ts), true );
				}
			}
		}
	}
	closedir( $dh );
} else {
	trace( &quot;no old log dir $dir_old to scan yet&quot; );
}

// scan current files for rotation
if( file_exists($dir_old) ) {
	trace( &quot;creating $dir_old&quot; );
	$succ = @mkdir( $dir_old, 0775, true );
	if( !$succ ) {
		trace( &quot;mkdir failed, aborting rotation&quot; );
		exit( 1 );
	}
}
if( is_dir($dir_log) ) {
	$dh = opendir( $dir_log );
	if( $dh !== FALSE ) {
		chdir( $dir_log );
		trace( &quot;scanning $dir_log for logs more than $cutoff_rotate old&quot; );
		$cutoff = strtotime( &quot;-$cutoff_delete&quot; );
		trace( &quot;cutoff is &quot;.date('r',$cutoff) );
		while( ($file = readdir($dh)) !== FALSE ) {
			if( is_dir($file) ) {
				trace( &quot;skipping $file&quot;, true );
				continue;
			} else {
				$ts = filemtime($file);
				if( $ts &lt; $cutoff ) {
					trace( &quot;rotating $file, &quot;.date('r',$ts), true );
					$succ = @rename( $file, $dir_old );
					if( !$succ )
						trace( &quot;failed to rotate $file!&quot; );
				} else {
					trace( &quot;ignoring $file, &quot;.date('r',$ts), true );
				}
			}
		}
	}
	closedir( $dh );
}
?&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ammonlauritzen.com/blog/2010/02/03/simple-two-step-logfile-rotation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>lazy php profiler</title>
		<link>http://ammonlauritzen.com/blog/2010/01/12/lazy-php-profiler/</link>
		<comments>http://ammonlauritzen.com/blog/2010/01/12/lazy-php-profiler/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 01:06:56 +0000</pubDate>
		<dc:creator>Ammon</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://ammonlauritzen.com/blog/?p=1096</guid>
		<description><![CDATA[Caveman profiling with a side of &#8220;where were you at 9pm on the night in question?&#8221; As always, season to taste.

&#60;?
$_profile_log = &#34;/tmp/php-profile.log&#34;;

function _profile() {
    static $fh;
    if( !isset($fh) ) {
        global $_profile_log;
        if( !file_exists($_profile_log) [...]]]></description>
			<content:encoded><![CDATA[<p>Caveman profiling with a side of &#8220;where were you at 9pm on the night in question?&#8221; As always, season to taste.</p>
<pre class="brush: php;">
&lt;?
$_profile_log = &quot;/tmp/php-profile.log&quot;;

function _profile() {
    static $fh;
    if( !isset($fh) ) {
        global $_profile_log;
        if( !file_exists($_profile_log) ) {
            @touch( $_profile_log );
            @chmod( $_profile_log, 0664 );
        }
        $fh = @fopen( $_profile_log, &quot;a&quot; );
    }
    if( !$fh )
        return false;

    $stack = debug_backtrace();
    if( $stack[1] )
        $base = $stack[1];
    else
        $base = $stack[0];
    $buf = $base['file'].&quot;:&quot;.$base['line'].&quot;, &quot;;
    if( $base['class'] )
        $buf .= $base['class'].$base['type'];
    $buf .= $base['function'];

    $buf = sprintf(&quot;[%s] %s\n&quot;,date(&quot;H:i:s&quot;),$buf);
    return @fwrite( $fh, $buf );
}
?&gt;
</pre>
<p><span id="more-1096"></span><br />
Sample use:</p>
<pre class="brush: php;">
&lt;?
require_once &quot;profiler.php&quot;;

// setup
function func() {
    _profile();
}

class obj {
    function method() {
        _profile();
    }
    function other_method() {
        func();
    }
    function indirect_method() {
        $this-&gt;method();
    }
}

$obj = new obj();

// actual invocation cases
_profile();
func();
obj::method();
$obj-&gt;method();
$obj-&gt;other_method();
$obj-&gt;indirect_method();
?&gt;
</pre>
<p>Output:</p>
<pre class="brush: plain;">
ammon@elzar:~$ cat /tmp/php-profile.log
[19:00:21] /home/ammon/test.php:20, _profile
[19:00:21] /home/ammon/test.php:21, func
[19:00:21] /home/ammon/test.php:22, obj::method
[19:00:21] /home/ammon/test.php:24, obj-&gt;method
[19:00:21] /home/ammon/test.php:13, func
[19:00:21] /home/ammon/test.php:16, obj-&gt;method
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ammonlauritzen.com/blog/2010/01/12/lazy-php-profiler/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>gearman 0.3 php extension api</title>
		<link>http://ammonlauritzen.com/blog/2009/05/26/gearman-03-php-extension-api/</link>
		<comments>http://ammonlauritzen.com/blog/2009/05/26/gearman-03-php-extension-api/#comments</comments>
		<pubDate>Tue, 26 May 2009 21:10:17 +0000</pubDate>
		<dc:creator>Ammon</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[gearman]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://ammonlauritzen.com/blog/?p=500</guid>
		<description><![CDATA[No real preamble to be made here. Gearman is a distributed job queuing system by the fine folks who brought us memcached. It is nicer than anything else I&#8217;ve looked at. I am attempting to switch one of my projects over to it (replacing a crufty curl + unix sockets + memcached monstrosity that attempted [...]]]></description>
			<content:encoded><![CDATA[<p>No real preamble to be made here. <a href='http://gearman.org'>Gearman</a> is a distributed job queuing system by the <a href='http://danga.com/'>fine folks</a> who brought us <a href='http://danga.com/memcached/'>memcached</a>. It is nicer than anything else I&#8217;ve looked at. I am attempting to switch one of my projects over to it (replacing a crufty curl + unix sockets + memcached monstrosity that attempted to do the same job).</p>
<p>The documentation is lacking, but if the discussion group is any indication, real docs are a high priority for the project team. Today, I visited the IRC channel to ask for a status update on docs for the PHP extension api (as opposed to the PEAR all-script api, whose auto-generated docs are broken). Turns out my suspicions were right. Documentation is a high priority and none currently exists for the api in question. However&#8230; I was informed that the classes support reflection&#8230; so <img src='http://ammonlauritzen.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>A quick grep of the source for the extension tells me that I am looking at four classes: GearmanClient, GearmanWorker, GearmanJob, and GearmanTask. A ridiculously short php script later&#8230;</p>
<pre class="brush: php;">
&lt;?
Reflection::export( new ReflectionClass('GearmanWorker') );
Reflection::export( new ReflectionClass('GearmanClient') );
Reflection::export( new ReflectionClass('GearmanJob') );
Reflection::export( new ReflectionClass('GearmanTask') );
?&gt;
</pre>
<p>And I can at least try to make a human readable list of available methods.</p>
<h3>GearmanWorker</h3>
<ul>
<li>__construct()</li>
<li>clone()</li>
<li>error()</li>
<li>returnCode()</li>
<li>setOptions( $option, $data )</li>
<li>addServer( $host, $port ) &#8211; both args optional, examples say defaults are localhost on port 4730.</li>
<li>addFunction( $function_name, $function, $data, $timeout ) &#8211; data and timeout optional</li>
<li>work()</li>
</ul>
<h3>GearmanClient</h3>
<ul>
<li>__construct()</li>
<li>clone()</li>
<li>error()</li>
<li>setOptions( $option, $data )</li>
<li>addServer( $host, $port ) &#8211; reflection says REQUIRED, however the provided examples and personal experience says otherwise</li>
<li>do( $function_name, $workload, $unique ) &#8211; unique is optional</li>
<li>doHigh( $function_name, $workload, $unique ) &#8211; unique is optional</li>
<li>doLow( $function_name, $workload, $unique ) &#8211; unique is optional</li>
<li>doJobHandle()</li>
<li>doStatus()</li>
<li>doBackground( $function_name, $workload, $unique ) &#8211; unique is optional</li>
<li>doHighBackground( $function_name, $workload, $unique ) &#8211; unique is optional</li>
<li>doLowBackground( $function_name, $workload, $unique ) &#8211; unique is optional</li>
<li>jobStatus( $job_handle )</li>
<li>echo( $workload )</li>
<li>addTask( $function_name, $workload, $data, $unique ) &#8211; data and unique are optional</li>
<li>addTaskHigh( $function_name, $workload, $data, $unique ) &#8211; data and unique are optional</li>
<li>addTaskLow( $function_name, $workload, $data, $unique ) &#8211; data and unique are optional</li>
<li>addTaskBackground( $function_name, $workload, $data, $unique ) &#8211; data and unique are optional</li>
<li>addTaskHighBackground( $function_name, $workload, $data, $unique ) &#8211; data and unique are optional</li>
<li>addTaskLowBackground( $function_name, $workload, $data, $unique ) &#8211; data and unique are optional</li>
<li>addTaskStatus( $job_handle, $data ) &#8211; data is optional</li>
<li>setWorkloadCallback( $callback )</li>
<li>setCreatedCallback( $callback)</li>
<li>setClientCallback( $callback)</li>
<li>setWarningCallback( $callback)</li>
<li>setStatusCallback( $callback)</li>
<li>setCompleteCallback( $callback)</li>
<li>setExceptionCallback( $callback)</li>
<li>setFailCallback( $callback)</li>
<li>clearCallbacks()</li>
<li>data()</li>
<li>setData( $data )</li>
<li>runTasks()</li>
</ul>
<h3>GearmanJob</h3>
<ul>
<li>__construct()</li>
<li>returnCode()</li>
<li>workload()</li>
<li>workloadSize()</li>
<li>warning( $warning )</li>
<li>status( $numerator, $denominator )</li>
<li>handle()</li>
<li>unique()</li>
<li>data( $data )</li>
<li>complete( $result )</li>
<li>exception( $exception )</li>
<li>fail()</li>
<li>functionName()</li>
<li>setReturn( $gearman_return_t )</li>
</ul>
<h3>GearmanTask</h3>
<ul>
<li>__construct()</li>
<li>returnCode()</li>
<li>create()</li>
<li>free()</li>
<li>function()</li>
<li>uuid()</li>
<li>jobHandle()</li>
<li>isKnown()</li>
<li>isRunning()</li>
<li>taskNumerator()</li>
<li>taskDenominator()</li>
<li>data()</li>
<li>dataSize()</li>
<li>takeData( $task_object ) &#8211; optional</li>
<li>sendData( $data )</li>
<li>recvData( $data_len )</li>
</ul>
<p>The extension also appears to expose all constants defined in the C api.</p>
<p>I have since added this to the official <a href='http://www.gearman.org/doku.php?id=php_reflection'>wiki</a> &#8211; so there are at least SOME docs on the site now <img src='http://ammonlauritzen.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://ammonlauritzen.com/blog/2009/05/26/gearman-03-php-extension-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>php autoload</title>
		<link>http://ammonlauritzen.com/blog/2008/10/28/php-autoload/</link>
		<comments>http://ammonlauritzen.com/blog/2008/10/28/php-autoload/#comments</comments>
		<pubDate>Tue, 28 Oct 2008 23:06:40 +0000</pubDate>
		<dc:creator>Ammon</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[rant]]></category>
		<category><![CDATA[style]]></category>

		<guid isPermaLink="false">http://ammonlauritzen.com/blog/?p=407</guid>
		<description><![CDATA[As of version 5.0, PHP has had the ability to dynamically include required classes as needed &#8211; without requiring the developer to manually include all possible dependencies beforehand. This means that in cases where your code execution never touches 39 of the 40 classes in the project, it loads, parses, and runs that much faster.
There [...]]]></description>
			<content:encoded><![CDATA[<p>As of version 5.0, PHP has had the ability to dynamically include required classes as needed &#8211; without requiring the developer to manually include all possible dependencies beforehand. This means that in cases where your code execution never touches 39 of the 40 classes in the project, it loads, parses, and runs that much faster.</p>
<p>There is a performance hit for actually having to call the <a href='http://php.net/autoload'>__autoload()</a> method, but if you&#8217;re in a situation where the hit for executing a few extra comparison calls is unacceptable&#8230; you probably aren&#8217;t developing in PHP in the first place <img src='http://ammonlauritzen.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Almost all of the php I&#8217;ve written in the last 2-3 years uses autoloading, and it has probably saved me hundreds of hours of aggravation.</p>
<p>In most of my projects, the first line of any script or class usually looks something like this:</p>
<pre class="brush: php;">
require_once &quot;/var/www/common/lib.php&quot;;
</pre>
<p>Then lib.php usually reads something like this:</p>
<pre class="brush: php;">
&lt;?
function __autoload( $class ) {
    include_once( &quot;$class.php&quot; );
}
?&gt;
</pre>
<p>And that is all that is strictly required to make the magic happen. It is fast, it is easy to understand, it is easy to use. You can use require_once() or include_once() and there is very little meaningful difference.</p>
<p>I&#8217;ve looked around the net and found several other attempts at improving on this simple mechanism. But they invariably overcomplicate things. They attempt to recurse source directories, cache filename->class differences to the filesystem, and otherwise turn what should be a simple filesystem operation that the php environment supports natively into a mess of exception handling and wheel reinvention.</p>
<p>There are obviously theoretical instances where you might want to have more than the one require_once/include_once line&#8230; but I&#8217;ve honestly never encountered one myself.</p>
<p>I mean, you could try to throw an exception if the file didn&#8217;t exist or otherwise failed to load&#8230; but nothing will happen. Failure to instantiate a nonexistant class is a fatal error in PHP, and will be handled as such with or without you &#8211; preempting any attempt at throwing an exception.</p>
<p>The only thing you can add is a bit of extra diagnostics or maybe logging to a separate location.</p>
<p>Assume that we have a file &#8216;test.php&#8217;:</p>
<pre class="brush: php;">
&lt;?
require_once &quot;autoload.php&quot;;
$frog = new Frog();
?&gt;
</pre>
<p>If autoload.php contains a simple simple autoload function that uses require_once(), and Frog.php doesn&#8217;t exist anywhere in your include path, the results will look something like this:</p>
<pre class="brush: plain;">
ammon@kif:~$ php test.php 

Warning: require_once(Frog.php): failed to open stream: No such file or directory in /home/ammon/autoload.php on line 3

Fatal error: require_once(): Failed opening required 'Frog.php' (include_path='.:/usr/share/php:/usr/share/pear') in /home/ammon/autoload.php on line 3
</pre>
<p>If we had used an include_once() call, the output is similar, but slightly more informative:</p>
<pre class="brush: plain;">
ammon@kif:~$ php test.php 

Warning: include_once(Frog.php): failed to open stream: No such file or directory in /home/ammon/autoload.php on line 3

Warning: include_once(): Failed opening 'Frog.php' for inclusion (include_path='.:/usr/share/php:/usr/share/pear') in /home/ammon/autoload.php on line 3

Fatal error: Class 'Frog' not found in /home/ammon/test.php on line 4
</pre>
<p>So that&#8217;s probably a bit more useful in tracking down the error. Require calls don&#8217;t return anything &#8211; they throw a fatal error on failure. Include calls, however, return FALSE on failure and TRUE if the file is (or, in the case of include_once, has already been) successfully included. So you can include_once() and write to a separate logfile (or to the output stream&#8230;) if you need more information than the fatal error already provides you.</p>
<h3>&lt;rant&gt;</h3>
<p>To those who insist on giving your classes and their containing files different names&#8230; umm. Wow.</p>
<p>If I have a class called DatabaseConnection, I&#8217;m going to put it in a file called DatabaseConnection.php. If I&#8217;m working with strange people who somehow don&#8217;t think that is explicit enough, I might call it DatabaseConnection.class.php and tweak the autoload method ever so slightly to compensate. There&#8217;s no good reason to put it in a file called projx-database_connection.incl or something. No. There isn&#8217;t.</p>
<p>If you want to organize your classes into a meaningful directory structure&#8230; good for you. Use PHP&#8217;s built-in <a href='http://php.net/get_include_path'>include_path</a> ini option. Don&#8217;t waste time trying to cascade down a directory structure searching for the classes &#8211; just make sure your includes are all in a set of reliable locations. You don&#8217;t actually have to edit the php.ini file and bounce Apache or your php-cgi processes, just define the additional include paths in the same file where you define your autoloader:</p>
<pre class="brush: php;">
set_include_path(
    get_include_path() . PATH_SEPARATOR .
    &quot;/var/www/includes&quot; . PATH_SEPARATOR .
    &quot;/var/www/includes/apple&quot; . PATH_SEPARATOR .
    &quot;/var/www/includes/banana&quot;
);
</pre>
<p>Naturally, you could turn that into some function calls to dynamically register and unregister directories, etc&#8230; but at that point, you&#8217;re probably hurting yourself again. If your codebase is being reorganized enough to make maintenance of the list of include dirs onerous without full time intervention, something else has probably already gone very wrong. At best, the code probably doesn&#8217;t work anyway, so any brief delay in updating the list can&#8217;t hurt any more than whatever else is happening.</p>
<h3>&lt;/rant&gt;</h3>
<p>But seriously. __autoload() is your friend. It will help clean up your code if you let it. It can help enforce naming conventions. It can even improve performance&#8230; so long as you refrain from using it to shoot yourself in the foot. <img src='http://ammonlauritzen.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://ammonlauritzen.com/blog/2008/10/28/php-autoload/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>php signals while selecting</title>
		<link>http://ammonlauritzen.com/blog/2008/10/27/php-signals-while-selecting/</link>
		<comments>http://ammonlauritzen.com/blog/2008/10/27/php-signals-while-selecting/#comments</comments>
		<pubDate>Mon, 27 Oct 2008 20:26:38 +0000</pubDate>
		<dc:creator>Ammon</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[gotcha]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[posix signals]]></category>
		<category><![CDATA[sockets]]></category>

		<guid isPermaLink="false">http://ammonlauritzen.com/blog/?p=399</guid>
		<description><![CDATA[So a fairly longstanding gripe of mine has been that PHP fails to execute registered signal handlers when it receives a signal in the middle of a blocking select call. Today, I finally bumped into a situation where I couldn&#8217;t just change the spec to avoid the situation&#8230; and I&#8217;ve finally figured out how to [...]]]></description>
			<content:encoded><![CDATA[<p>So a fairly longstanding gripe of mine has been that PHP fails to execute registered signal handlers when it receives a signal in the middle of a blocking select call. Today, I finally bumped into a situation where I couldn&#8217;t just change the spec to avoid the situation&#8230; and I&#8217;ve finally figured out how to make it work.</p>
<p>The bug has been reported <a href='http://bugs.php.net/44614'>here</a>, where it was ignored for a few months before being shot down and ignored some more as per php dev team regulations.</p>
<p>Sample code given by the reporter of the bug is markedly similar to the situations I&#8217;ve encountered the problem:</p>
<pre class="brush: php;">
pcntl_signal(SIGINT, &quot;sig_handler&quot;);
$sock = socket_create_listen($port);
$read_socks = array($sock);
$n = NULL;
$foo = socket_select($read_socks, $n, $n, NULL);
</pre>
<p>By filling in his blanks, my first test case looks something like this:</p>
<pre class="brush: php;">
&lt;?
function sig_handler($signo) {
        echo &quot;received sig #$signo\\\n&quot;;
}
pcntl_signal( SIGINT, &quot;sig_handler&quot; );

$socket = socket_create_listen( 1234 );
$r = array( $socket );
$n = NULL;
while( true ) {
        $foo = socket_select( $r, $n, $n, NULL );
        echo &quot;select returned '$foo'\\\n&quot;;
}
?&gt;
</pre>
<p>When executing the script and pressing ^C (which sends SIGINT), the following occurs:</p>
<pre class="brush: plain;">
ammon@morbo:~$ php sigtest.php
PHP Warning:  socket_select(): unable to select [4]: Interrupted system call in /home/ammon/sigtest.php on line 13
select returned ''
</pre>
<p>Ok, so the warning is to be expected, and we can easily squelch that.</p>
<p>The real problem is that the signal handler never runs.</p>
<p>However&#8230; for the first time in my life, a response to a php bug report proves enlightening. The dev who answered this ticket provides his sample code and says he can&#8217;t duplicate the bug. Upon looking at the differences between their code, only one difference stands out:</p>
<pre class="brush: php;">
declare(ticks=1);
</pre>
<p>The <a href='http://php.net/declare'>declare(ticks)</a> directive is deprecated as of php 5.3 and will not be with us in php 6.0. Ticks are an unreliable, unpredictable, and generally bad thing in php. I&#8217;ve neither successfully used them nor seen a successful and justified use.</p>
<p>That being said&#8230; turning the tick on but not telling it to do anything appears to address the problem of discarded interrupts:</p>
<pre class="brush: php;">
&lt;?
declare(ticks=1);

function sig_handler($signo) {
        echo &quot;received sig #$signo\\\n&quot;;
}
pcntl_signal( SIGINT, &quot;sig_handler&quot; );

$socket = socket_create_listen( 1234 );
$r = array( $socket );
$n = NULL;
while( true ) {
        $foo = @socket_select( $r, $n, $n, NULL );
        echo &quot;select returned '$foo'\\\n&quot;;
}
?&gt;
</pre>
<p>And execution:</p>
<pre class="brush: plain;">
ammon@morbo:~$ php sigtest.php
received sig #2
select returned ''
</pre>
<p>Which is precisely the desired behavior.</p>
<p>I don&#8217;t know what the performance hit for turning ticks on is, I haven&#8217;t had time to research this. But I can confirm that by declaring ticks globally, it does work in an OO environment as well:</p>
<pre class="brush: php;">
&lt;?
declare(ticks=1);

class signal_tester {
    function __construct() {
        pcntl_signal( SIGINT, array(&amp;$this,&quot;sig_handler&quot;) );
        $this-&gt;start();
    }

    function sig_handler($signo) {
        echo &quot;received sig #$signo\\\n&quot;;
    }

    function start() {
        $socket = socket_create_listen( 1234 );
        $r = array( $socket );
        $n = NULL;
        while( true ) {
            $foo = @socket_select( $r, $n, $n, NULL );
            echo &quot;select returned '$foo'\\\n&quot;;
        }
    }
}

$test = new signal_tester();
?&gt;
</pre>
<p>Executing and hitting ^C:</p>
<pre class="brush: plain;">
ammon@morbo:~$ php sigtest.php
received sig #2
select returned ''
</pre>
<p>After a few minutes of largely unscientific testing, it appears that turning ticks on globally costs a whopping 4 bytes of ram and causes the script to occasionally consume more cpu than the top process I used to monitor it. So&#8230; at first glance the cost is pretty negligible and all I can say is that if you ever need to handle signals (SIGTERM, SIGHUP, etc&#8230;) from within a blocking select call in php, it looks like declare ticks is the only option for now.</p>
<p>I did the initial tests in 5.1.6, but can confirm the same behavior in 5.2.5. I don&#8217;t know how the behavior is going to be in 5.3, since I don&#8217;t run alpha releases on my servers but my gut likes to think that it will continue to work the same for now&#8230; and will hopefully not break until 6.0 (when everything else will explode for a few years). Shrug.</p>
]]></content:encoded>
			<wfw:commentRss>http://ammonlauritzen.com/blog/2008/10/27/php-signals-while-selecting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>php tail</title>
		<link>http://ammonlauritzen.com/blog/2008/05/27/php-tail/</link>
		<comments>http://ammonlauritzen.com/blog/2008/05/27/php-tail/#comments</comments>
		<pubDate>Tue, 27 May 2008 19:08:21 +0000</pubDate>
		<dc:creator>Ammon</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://ammonlauritzen.com/blog/?p=389</guid>
		<description><![CDATA[I have a php script that frequently needs to email me the last few lines of a log file. I can&#8217;t afford to exec() a binary tail process, so the solution has to be in pure php.
Originally, the files in question never exceeded more than a few thousand lines. Unfortunately, I am encountering cases now [...]]]></description>
			<content:encoded><![CDATA[<p>I have a php script that frequently needs to email me the last few lines of a log file. I can&#8217;t afford to exec() a binary tail process, so the solution has to be in pure php.</p>
<p>Originally, the files in question never exceeded more than a few thousand lines. Unfortunately, I am encountering cases now where the files are now occasionally 50,000 lines or longer. This causes PHP&#8217;s memory consumption to explode.</p>
<p><i>Note: Code snippets provided here are not fully functional standalone shell scripts. The scripts I ran to benchmark the algorithms contain some rudimentary setup logic that is not important here, so has not been included.</i></p>
<p>My original method:</p>
<pre class="brush: php;">
// tail-file.php
$arr = @file( $fname, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
$arr = array_slice($arr, -$lines);
$buf = implode(&quot;\\\n&quot;,$arr);
</pre>
<p>This is easy to understand and is pretty fast, all things considered. Unfortunately, the memory footprint for loading a file into an array is obscene. Loading a 4400 line log file with this method could consume more than 17mb of ram. 50,000 line files easily stressed the 256mb limit I am able to provide the process.</p>
<p>So, the obvious solution to the memory consumption is to avoid loading the entire file at once. What if we kept a rotating list of lines in the file?</p>
<pre class="brush: php;">
// tail-array.php
$arr = array_fill( 0, $lines+1, &quot;\\\n&quot; );

$fp = fopen($fname, &quot;r&quot;);
while( !feof($fp) ) {
    $line = fgets($fp, 4096);
    $arr[] = $line; // faster than array_push()
    array_shift($arr);
}
fclose($fp);
$buf = implode(&quot;&quot;,$arr);
</pre>
<p>This method works by keeping the $lines-many most recent lines of the file in an array. Memory consumption remains sane, but the performance hit for performing so many array pushes and shifts is bad. Really bad. With small files, I can&#8217;t notice any difference between this method and the file() method&#8230; but with longer files, it adds up quickly.</p>
<p>Given a 51 line, 4kb file, an average execution ($lines = 20) might look like this:</p>
<pre class="brush: plain;">
ammon@zapp:~$ time ./tail-file.php a.log &gt;/dev/null

real    0m0.015s
user    0m0.009s
sys     0m0.007s

ammon@zapp:~$ time ./tail-array.php a.log &gt;/dev/null

real    0m0.016s
user    0m0.010s
sys     0m0.006s
</pre>
<p>Comparable enough. But given a 50,004 line (3.3mb) log file:</p>
<pre>
ammon@zapp:~$ time ./tail-file.php b.log >/dev/null                  

real    0m0.079s
user    0m0.058s
sys     0m0.021s

ammon@zapp:~$ time ./tail-array.php b.log >/dev/null                 

real    0m0.119s
user    0m0.112s
sys     0m0.007s
</pre>
<p>The difference becomes quite clear. However&#8230; what if my log file grows obscenely large? I&#8217;ve got a 9 million line log file (1.6gb) lying around to test with&#8230;</p>
<pre>
ammon@zapp:~$ time ./tail-file.php c.log >/dev/null

real    0m0.015s
user    0m0.008s
sys     0m0.008s

ammon@zapp:~$ time ./tail-array.php c.log >/dev/null                 

real    0m19.351s
user    0m18.545s
sys     0m0.803s
</pre>
<p>The file() method crashes because it can&#8217;t allocate enough ram to hold a 9 million element array and the array method takes almost 20 seconds to execute. It&#8217;s slow&#8230; but at least it works.</p>
<p>Of course, there are other methods. The one I finally settled on is this:</p>
<pre class="brush: php;">
// tail-seek.php
$fp = fopen($fname, &quot;r&quot;);
$lines_read = 0;
if( $fp !== FALSE ) {
    fseek( $fp, 0, SEEK_END );
    $pos = $eof = ftell($fp);
    do {
        --$pos;
        fseek($fp, $pos);
        $c = fgetc($fp);
        if( $c == &quot;\\\n&quot; )
            $lines_read++;
    } while( $pos &gt; 0 &amp;&amp; $lines_read &lt;= $lines );
    $buf = fread($fp, $eof-$pos);
}
fclose($fp);
</pre>
<p>This method doesn&#8217;t waste time reading the bulk of the file. It jumps to the end and scans backward until enough newlines have been located. The only problem here is that your average filesystem isn&#8217;t optimized for reading backwards&#8230; but since we&#8217;re not really reading very much data, it doesn&#8217;t much matter.</p>
<pre>
ammon@zapp:~$ time ./tail-seek.php a.log >/dev/null

real    0m0.017s
user    0m0.009s
sys     0m0.008s

ammon@zapp:~$ time ./tail-seek.php b.log >/dev/null                  

real    0m0.017s
user    0m0.008s
sys     0m0.010s

ammon@zapp:~$ time ./tail-seek.php c.log >/dev/null                  

real    0m0.023s
user    0m0.015s
sys     0m0.008s
</pre>
<p>Performance is a trifle slower on small files, but it&#8217;s astronomically better on long ones. This is similar to the method used by most unix &#8216;tail&#8217; commands, and is the clear winner for actual use in my application.</p>
<p>Of course, it needs a bit of cleanup from the state I&#8217;ve provided it in, and isn&#8217;t appropriate for all environments&#8230; but it&#8217;s a trifle better than requiring 20 seconds and 20gb of ram to execute <img src='http://ammonlauritzen.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://ammonlauritzen.com/blog/2008/05/27/php-tail/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>flash policy service daemon</title>
		<link>http://ammonlauritzen.com/blog/2008/04/22/flash-policy-service-daemon/</link>
		<comments>http://ammonlauritzen.com/blog/2008/04/22/flash-policy-service-daemon/#comments</comments>
		<pubDate>Tue, 22 Apr 2008 09:05:10 +0000</pubDate>
		<dc:creator>Ammon</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[sysadmin]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[networking]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[sockets]]></category>

		<guid isPermaLink="false">http://ammonlauritzen.com/blog/?p=362</guid>
		<description><![CDATA[Sorry it took me so long to post this, but Wordpress 2.5 doesn&#8217;t seem to like me trying to upload gz/zip files, so I had to upload the source manually.
Well, it&#8217;s been months since I promised to post some usable socket policy service code, so I will.
The script here is meant to serve as a [...]]]></description>
			<content:encoded><![CDATA[<p><i>Sorry it took me so long to post this, but Wordpress 2.5 doesn&#8217;t seem to like me trying to upload gz/zip files, so I had to upload the source manually.</i></p>
<p>Well, it&#8217;s been months since <a href='http://ammonlauritzen.com/blog/2007/12/13/new-flash-security-policies/'>I promised</a> to post some usable socket policy service code, so I will.</p>
<p>The script here is meant to serve as a good starting point for people whose servers need to allow flash clients to make socket connections. I have not actually used this exact code in a production environment, but I have been using code that is 99% identical for a while now. I am confident that any blatant flaws are the result of simple copy-paste errors as I compiled the package. Please let me know if you find any.</p>
<p>I <u>have</u> however, stress tested the heck out of this service. One instance successfully served up over 16000 policy file requests fed into it as rapidly as I could send them. The same networking code has also handled requests from at least 100 different hosts at roughly the same time.</p>
<p>Everything has been combined into a single cli php script that requires no special installation. Just plop it down on the server and run it as root. It will take care of the rest. The config defaults should be safe, but you probably want to specify them more clearly &#8211; just to be safe.</p>
<p>The daemon is made of three classes:</p>
<ul>
<li><b>Logger</b> &#8211; A rudimentary log file management class that I copy from project to project in one form or another. The included version is stripped down from some of the other versions I&#8217;ve written, and I&#8217;m planning on releasing a more feature-rich version in the future.</li>
<li><b>Daemon</b> &#8211; A simple class for daemonizing a process. Adapted and re-adapted countless times from an original php4 class I found on the net a few years ago by some guy named Seth (whose email domain no longer exists).</li>
<li><b>FlashPolicyService</b> &#8211; The meat and potatoes, a child of Daemon. Mostly, this is just the requisite networking code and glue to make everything work together.</li>
</ul>
<p>As with any of my other code, this is licensed under <a href='http://creativecommons.org/licenses/by/3.0/'>CC Attribution 3.0</a>.</p>
<p>Download:</p>
<ul>
<li><a href='http://ammonlauritzen.com/FlashPolicyService-09c.zip'>FlashPolicyService-09c.zip</a> (4.4kb)</li>
</ul>
<p>Source code after the jump.<br />
<span id="more-362"></span></p>
<pre class="brush: php;">
#!/usr/local/bin/php
&lt;?php
/**
 * Flash Policy Service v0.9.c
 *
 * This script listens for &lt;policy-file-request/&gt; on port 843 and serves up
 * an xml crossdomain policy file. This sort of service is necessary if any
 * flash content is going to connect to sockets on the running host.
 *
 * I have made every effort to package everything you need into a single
 * file here, even though it could easily have been split into 3 or more
 * scripts.
 *
 * Requirements:
 *  - PHP 5 with sockets, pcntl, and posix extensions
 *  - Root access (to bind to a &lt;1024 port)
 *
 * Use:
 *  Simply execute the script from the command line as root:
 *    # ./FlashPolicyService.php
 *  You can enable debug mode by invoking the script with '-d' as a parameter:
 *    # ./FlashPolicyService.php -d
 *  To stop the daemon, simply send it a SIGTERM and it should attempt to
 *  exit cleanly.
 *
 *  If you get 'bad interpreter' errors or the like, change the #! line to
 *  reflect the actual installed location of your php cli.
 *
 * Configuration:
 *  At present, there aren't very many config options. Simply edit the
 *  section immediately following this header. Options are commented.
 *
 * License:
 *  This code is made available under a Creative Commons Attribution 3.0
 *  License. Basically, you can use it however you like, but I would
 *  appreciate some credit when you do.
 *
 * Disclaimer:
 *  I make no guarantees that this code won't make your server explode in a
 *  shower of blue flames. However, I don't expect that it will. I am actually
 *  confident that this code will be helpful.
 *
 *  That said, this is still my beta release. If you find any bugs, please
 *  let me know so I can fix them.
 *
 * - Ammon Lauritzen [Apr 21, '08]
 *   http://ammonlauritzen.com/blog/2008/04/22/flash-policy-service-daemon/
 *
 * Changelog
 * 0.9.c
 *   - Fixed some typoes that were the result of how I combined everything
 *     into a single file. Thanks Alex!
 * 0.9.b
 *   - Original version to be posted at this url.
 * 0.9.a
 *   - Original proof of concept code posted online.
 */

/*** Config ***/

// where should we save the log output?
$log_filename = &quot;/tmp/flash-policy.log&quot;;

// uncomment these lines to choose which user to run the daemon as
// default behavior is to look up and attempt to run as 'nobody'
# $daemon_uid = 99;
# $daemon_gid = 99;

// set this if you want to use an external file in stead of the default
$xml_filename = &quot;&quot;;
$default_xml =
	'&lt;'.'?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?'.'&gt;'.
    '&lt;cross-domain-policy xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:noNamespaceSchemaLocation=&quot;http://www.adobe.com/xml/schemas/PolicyFileSocket.xsd&quot;&gt;'.
        '&lt;allow-access-from domain=&quot;*&quot; to-ports=&quot;*&quot; secure=&quot;false&quot; /&gt;'.
        '&lt;site-control permitted-cross-domain-policies=&quot;all&quot; /&gt;'.
    '&lt;/cross-domain-policy&gt;';

/*** You shouldn't have to edit anything below here ***/

/////////////////////////////////////////////////////////////////////////////
class Logger {
	public function __construct( $logfile ) {
        $this-&gt;logfile = $logfile;
        $this-&gt;open_log();
    }// end: constructor

    public function __destruct() {
        @fflush( $this-&gt;fh );
        @fclose( $this-&gt;fh );
    }// end: destructor

    public function log( $msg ) {
		// deal with redundant log spam
		if( $msg == $this-&gt;last_msg ) {
			$this-&gt;last_msg_count++;
			return;
		} else if( $this-&gt;last_msg_count ) {
			$this-&gt;write( &quot;Last message repeated &quot;.$this-&gt;last_msg_count.&quot; times.&quot; );
		}
		$this-&gt;lasg_msg = $msg;
		$this-&gt;last_msg_count = 0;

		// actually write the log message out
		$this-&gt;write( $msg );
	}// end: log

	private function write( $msg ) {
        $msg = sprintf(&quot;[%s] %s\\n&quot;,date(&quot;y-m-d H:i:s&quot;),$msg);
        $succ = @fwrite( $this-&gt;fh, $msg );
        if( $succ === FALSE ) {
            echo $msg;
        }
    }// end: write

	private function open_log() {
        if( !file_exists($this-&gt;logfile) ) {
            touch( $this-&gt;logfile );
            chmod( $this-&gt;logfile, 0664 );
        }
        $this-&gt;fh = @fopen( $this-&gt;logfile, &quot;a&quot; );
    }
}// end: logger class

/////////////////////////////////////////////////////////////////////////////
class Daemon {
	public function __construct() {
		error_reporting(0);
		set_time_limit(0);

		global $log_filename, $pid_filename;
		$this-&gt;logger = new Logger( $log_filename );
		$this-&gt;pid_filename = $pid_filename;

		$this-&gt;log_tag = $this-&gt;daemon_tag = &quot;launcher&quot;;
		$this-&gt;debug( &quot;constructed&quot;, $this-&gt;daemon_tag );
	}// end: constructor

	public function __destruct() {
		$this-&gt;debug( &quot;destructing&quot;, $this-&gt;daemon_tag );
	}// end: destructor

	protected function log( $msg, $tag = false ) {
		if( $tag == false )
			$tag = $this-&gt;log_tag;
		$this-&gt;logger-&gt;log( $tag.&quot;: &quot;.$msg );
	}// end: log
	protected function debug( $msg, $tag = false ) {
		if( DEBUG )
			$this-&gt;log( $msg, $tag );
	}// end: debug

	protected function main() {
		$this-&gt;log( &quot;override main() in daemon subclass&quot;, $this-&gt;daemon_tag );
		$this-&gt;stop();
	}// end: main

	public function start() {
		$this-&gt;log( &quot;starting daemon&quot;, $this-&gt;daemon_tag );
		if( !$this-&gt;_start() ) {
			$this-&gt;log( &quot;unable to start daemon&quot;, $this-&gt;daemon_tag );
			return;
		}

		// report execution details
		$this-&gt;log( &quot;uid = &quot;.posix_getuid().&quot;, gid = &quot;.posix_getgid() );
		$this-&gt;log( &quot;cwd = &quot;.getcwd() );

		// invoke main loop
		$this-&gt;running = true;
		while( $this-&gt;running ) {
			$this-&gt;main();
		}
	}// end: start
	private function _start() {
		if( !$this-&gt;_fork() ) {
			return false;
		}// end: try to fork

		if( !posix_setsid() ) {
			$this-&gt;log( &quot;unable to setsid()&quot;, $this-&gt;daemon_tag );
			return false;
		}// end: try to set sid

		if( !$this-&gt;_suid() ) {
			return false;
		}// end: try to set uid

		// register signal handler
		declare(ticks = 1);
		pcntl_signal( SIGTERM, array(&amp;$this, &quot;on_sigterm&quot;) );
		// chdir somewhere moderately safe by default
		chdir( '/tmp' );
		return true;
	}// end: _start
	private function _fork() {
		$this-&gt;log( &quot;forking...&quot;, $this-&gt;daemon_tag );
		$pid = pcntl_fork();
		if( $pid == -1 ) {
			// error
			$this-&gt;log( &quot;unable to fork&quot;, $this-&gt;daemon_tag );
			return false;
		} else if( $pid ) {
			// parent
			$this-&gt;debug( &quot;done with parent&quot;, $this-&gt;daemon_tag );
			exit( 0 );
		} else {
			// child
			$this-&gt;daemon_tag = &quot;daemon&quot;;
			$this-&gt;child = true;
			$this-&gt;pid = posix_getpid();
			$this-&gt;debug( &quot;child pid = &quot;.$this-&gt;pid );
			return true;
		}
	}// end: _fork
	private function _suid() {
		global $daemon_uid, $daemon_gid;
		if( !isset($daemon_uid) || !isset($daemon_gid) ) {
			// we didn't get a uid/gid, try to make one up
			$this-&gt;debug( &quot;searching for info on 'nobody'&quot;, $this-&gt;daemon_tag );
			$res = posix_getpwnam(&quot;nobody&quot;);
			if( $res !== FALSE ) {
				$uid = $res['uid'];
				$gid = $res['gid'];
			} else {
				// the 'nobody' user doesn't exist on this system, refuse
				// to daemonize as root
				$this-&gt;log( &quot;unable to find info on 'nobody' user&quot;, $this-&gt;daemon_tag );
				return false;
			}
		} else {
			$this-&gt;debug( &quot;got uid/gid of $daemon_uid/$daemon_gid&quot;, $this-&gt;daemon_tag );
			$uid = $daemon_uid;
			$gid = $daemon_gid;
		}
		// actually try to switch now
		if( !posix_setgid($gid) ) {
			$this-&gt;log( &quot;unable to set gid to &quot;.$gid, $this-&gt;daemon_tag );
			return false;
		} else if( !posix_setuid($uid) ) {
			$this-&gt;log( &quot;unable to set uid to &quot;.$uid, $this-&gt;daemon_tag );
			return false;
		} else {
			return true;
		}
	}// end: _suid

	public function stop() {
		$this-&gt;log( &quot;stopping daemon&quot;, $this-&gt;daemon_tag );
		$this-&gt;running = false;
	}// end: stop

	protected function on_sigterm( $sig ) {
		if( $sig == SIGTERM ) {
			$this-&gt;log( &quot;got SIGTERM&quot;, $this-&gt;daemon_tag );
			$this-&gt;stop();
			exit( 0 );
		}
	}// end: on_sigterm
}// end: daemon class

/////////////////////////////////////////////////////////////////////////////
class FlashPolicyService extends Daemon {
	public function __construct() {
		parent::__construct();
		$this-&gt;log_tag = &quot;fps&quot;;
		$this-&gt;debug( &quot;constructing&quot; );

		$this-&gt;connections = array();
		$this-&gt;request_str = &quot;&lt;policy-file-request/&gt;&quot;;
		$this-&gt;port = 843;

		// get our xml
		global $xml_filename, $default_xml;
		if( strlen($xml_filename) == 0 || !file_exists($xml_filename) ) {
			$this-&gt;log( &quot;unable to read xml from '$xml_filename', using default&quot; );
			$this-&gt;xml = $default_xml;
		} else {
			$this-&gt;log( &quot;reading policy xml from $xml_filename&quot; );
			$this-&gt;xml = file_get_contents( $xml_filename );
		}
		$this-&gt;debug( &quot;policy xml: &quot;.$this-&gt;xml );
		// make sure we're null terminated
		$this-&gt;xml = trim($this-&gt;xml).&quot;\\n\\0&quot;;

		// and get going
		$this-&gt;init();
	}// end: constructor

	public function __destruct() {
		parent::__destruct();
		if( $this-&gt;sock )
			@fclose($this-&gt;sock);
	}// end: destructor

	private function init() {
		$this-&gt;debug( &quot;init...&quot; );
		if( $this-&gt;check_socket() ) {
			parent::start();
		} else {
			$this-&gt;log( &quot;not starting daemon&quot; );
		}
	}// end: init

	protected function main() {
		if( $this-&gt;sock ) {
			while( true ) {
				$this-&gt;accept_socket();
			}
		} else {
			$this-&gt;log( &quot;server socket is closed?!&quot; );
			parent::stop();
		}
		// paranoia to keep from absolutely hosing cpu if something goes wrong
		usleep( 10000 );	// 10ms
	}// end: main

	private function check_socket() {
		$this-&gt;sock = @socket_create( AF_INET, SOCK_STREAM, SOL_TCP );
		if( !$this-&gt;sock ) {
			$this-&gt;log( &quot;unable to create socket&quot; );
		} else {
			$succ = @socket_bind( $this-&gt;sock, &quot;0.0.0.0&quot;, $this-&gt;port );
			if( !$succ ) {
				$this-&gt;log( &quot;unable to bind to port &quot;.$this-&gt;port );
			} else {
				$backlog = 100;
				$succ = @socket_listen( $this-&gt;sock, $backlog );
				if( !$succ ) {
					$this-&gt;log( &quot;unable to listen with backlog of $backlog&quot; );
				} else {
					// everything's good
					return true;
				}
			}// end: able to bind
		}// end: able to create socket

		// if we got here, it's an error. abort.
		$errno = socket_last_error( $this-&gt;sock );
		$errstr = socket_strerror( $errno );
		$this-&gt;log( &quot;socket error: $errno: $errstr&quot; );
		return false;
	}// end: check_socket

	private function accept_socket() {
		$r_socks = array_merge( array($this-&gt;sock), $this-&gt;connections );
		$this-&gt;debug( &quot;selecting on &quot;.count($r_socks).&quot; sockets&quot; );

		// block until something interesting happens
		$select = @socket_select( $r_socks, $w_socks = NULL, $e_socks = NULL, NULL );
		if( !$select )
			return;

		// did we get a new connection?
		if( in_array($this-&gt;sock, $r_socks) ) {
			$conn = @socket_accept( $this-&gt;sock );
			if( $conn !== false )
				@socket_getpeername( $conn, $addr );
			$this-&gt;log( &quot;connection accepted from $addr, $conn&quot; );
			$this-&gt;connections[] = $conn;
		}// end: got a new connection

		// check for policy requests
		foreach( $r_socks as $conn ) {
			// ignore the server socket
			if( $conn == $this-&gt;sock )
				continue;

			// read from the client
			$data = @socket_read( $conn, 1024 );
			if( $data === FALSE ) {
				$this-&gt;log( &quot;got disconnect from $conn&quot; );
			}// end: client closed connection
			else {
				$this-&gt;debug( &quot;read '&quot;.trim($data).&quot;' from $conn&quot; );
				if( strpos($data, $this-&gt;request_str) !== FALSE ) {
					$this-&gt;log( &quot;sending policy xml to $conn&quot; );
					@socket_write( $conn, $this-&gt;xml );
				} else {
					$this-&gt;log( &quot;got invalid request from $conn&quot; );
				}
			}// end: got data from the client

			// and always disconnect after having read something, whether
			// it was a valid request or not - especially if it wasn't <img src='http://ammonlauritzen.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />
			@socket_close( $conn );
			$key = array_search( $conn, $this-&gt;connections );
			if( $key !== FALSE )
				unset( $this-&gt;connections[$key] );
		}// end: foreach socket
	}// end: accept_socket

}// end: flash policy service class

/////////////////////////////////////////////////////////////////////////////
/**
 * Actual execution code here. This checks if the php install has all of our
 * requisite extensions, makes sure we're launching as root, and checks if
 * debug mode was requested before actually starting the daemon.
 */

// make sure we have required extensions
$required_extensions = array( &quot;sockets&quot;, &quot;posix&quot;, &quot;pcntl&quot; );
$missing_extension = false;
foreach( $required_extensions as $ext ) {
	if( !extension_loaded($ext) ) {
		echo &quot;Missing required php extension '$ext'.\n&quot;;
		$missing_extension = true;
	}
}
if( $missing_extension ) {
	exit( 1 );
}

// make sure we launch as root, otherwise we can't bind to 843
if( posix_getuid() != 0 || posix_getgid() != 0 ) {
	echo &quot;Policy service must be started as root.\n&quot;;
	exit( 1 );
}

// see if we're in debug mode
define( &quot;DEBUG&quot;, in_array('-d',$argv) );

// start the daemon
$fps = new FlashPolicyService();
?&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ammonlauritzen.com/blog/2008/04/22/flash-policy-service-daemon/feed/</wfw:commentRss>
		<slash:comments>43</slash:comments>
		</item>
		<item>
		<title>lazy image browser</title>
		<link>http://ammonlauritzen.com/blog/2008/03/21/lazy-image-browser/</link>
		<comments>http://ammonlauritzen.com/blog/2008/03/21/lazy-image-browser/#comments</comments>
		<pubDate>Fri, 21 Mar 2008 17:26:50 +0000</pubDate>
		<dc:creator>Ammon</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://ammonlauritzen.com/blog/2008/03/21/lazy-image-browser/</guid>
		<description><![CDATA[The other day, I heard a few people talking about needing an easy way to browse images on a remote Apache server that has Indexes disabled.
They had a ~20 line php script that they were dropping into each directory in order to generate indices. The problem came when they started organizing the images into subdirectories. [...]]]></description>
			<content:encoded><![CDATA[<p>The other day, I heard a few people talking about needing an easy way to browse images on a remote Apache server that has Indexes disabled.</p>
<p>They had a ~20 line php script that they were dropping into each directory in order to generate indices. The problem came when they started organizing the images into subdirectories. Eventually, it became necessary to copy the new script into a mind-bogglingly large number of directories. Inevitably, dirs were missed, etc&#8230;</p>
<p>I interjected that I could probably fix their problem in 30 minutes.</p>
<p>So I did.</p>
<pre class="brush: php;">
&lt;?
$base = getcwd();
$subdir = trim($_GET['dir']);

$dir = realpath(&quot;$base/$subdir&quot;);
$valid = strpos($dir, $base);
if( !$dir || $valid === FALSE || $valid != 0 )
	die();

$imgdir = dirname($_SERVER['SCRIPT_NAME']);

echo &quot;&lt;h3&gt;$subdir&lt;/h3&gt;\\\n&quot;;
$dirs = &quot;&quot;;
$imgs = &quot;&lt;hr/&gt;\\\n&quot;;

if( file_exists($dir) &amp;&amp; is_dir($dir) ) {
	$dh = opendir($dir);
	while( false !== ($file = readdir($dh)) ) {
		if( $file == &quot;.&quot; || $file == &quot;..&quot; || $file == &quot;.svn&quot; || substr($file,-4) == &quot;.php&quot; )
			continue;
		if( is_dir(&quot;$base/$subdir/$file&quot;) ) {
			$dirs .= &quot;&lt;span&gt;|&lt;a href='?dir=$subdir/$file'&gt;$file&lt;/a&gt;|&lt;/span&gt;\\\n&quot;;
		} else {
			$imgs .= &quot;&lt;div style='float:left; margin:15px;'&gt;&lt;a href='$imgdir/$subdir/$file'&gt;&lt;img style='border: none;' src='$imgdir/$subdir/$file'/&gt;&lt;/a&gt;&lt;/div&gt;\\\n&quot;;
		}
	}
}

echo $dirs;
echo $imgs;
?&gt;
</pre>
<p>It&#8217;s not elegant. It&#8217;s not pretty. It has plenty of room for improvement &#8211; it&#8217;ll generate links to Windows explorer thumbnail db&#8217;s, etc&#8230; But it is fast and should be moderately secure. Just drop it in the root directory of your image structure and you&#8217;re good.</p>
]]></content:encoded>
			<wfw:commentRss>http://ammonlauritzen.com/blog/2008/03/21/lazy-image-browser/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>new flash security policies</title>
		<link>http://ammonlauritzen.com/blog/2007/12/13/new-flash-security-policies/</link>
		<comments>http://ammonlauritzen.com/blog/2007/12/13/new-flash-security-policies/#comments</comments>
		<pubDate>Thu, 13 Dec 2007 22:14:20 +0000</pubDate>
		<dc:creator>Ammon</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[sysadmin]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[networking]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[rant]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://ammonlauritzen.com/blog/2007/12/13/new-flash-security-policies/</guid>
		<description><![CDATA[So&#8230; I am not happy with Adobe right now. With the push of Flash Player 9,0,115,0 &#8220;moviestar&#8221;, which included such awesome features as H.264 and AAC codec support and improvements to fullscreen mode, they kind of ambushed me with some sweeping changes to their security policy.
I&#8217;d been running pre-release nightly builds of the player since [...]]]></description>
			<content:encoded><![CDATA[<p>So&#8230; I am not happy with Adobe right now. With the push of Flash Player 9,0,115,0 &#8220;moviestar&#8221;, which included such awesome features as <a href='http://www.adobe.com/devnet/flashplayer/articles/hd_video_flash_player.html'>H.264 and AAC</a> codec support and <a href='http://www.adobe.com/devnet/flashplayer/articles/full_screen_mode.html'>improvements to fullscreen mode</a>, they kind of ambushed me with some sweeping changes to their security policy.</p>
<p>I&#8217;d been running pre-release nightly builds of the player since 9,0,60,x&#8230; and had noticed some strange warnings. Mysterious &#8220;Socket Security Error #2048&#8243; exceptions that were being thrown at random &#8211; even though I was serving an appropriate (for the time) crossdomain.xml file, unexplained timeouts attempting to talk to an xml socket server when I was very clearly not attempting to do any such thing, etc&#8230; My regularly repeated attempts to find documentation on what the warnings actually meant proved fruitless. I believe that is because <a href='http://www.adobe.com/devnet/flashplayer/articles/fplayer9_security.html'>the appropriate document</a> was not actually released to the public until 9,0,115,0 was released.</p>
<p>Now, the bit where they improved the format for <a href='http://marstonstudio.com/index.php/2007/12/06/new-security-policy-settings-in-flash-moviestar/'>crossdomain.xml</a> files doesn&#8217;t really affect me one way or the other. I approve of the improvements but could really care less in this case. They don&#8217;t really affect anything I&#8217;m doing.</p>
<p>The part that really chaps my hide is the fact that they&#8217;ve completely redone the way that socket security policies are handled. The important parts:</p>
<blockquote>
<ul>
<li>A SWF file may no longer make a socket connection to its own domain without a socket policy file. Prior to version 9,0,115,0, a SWF file was permitted to make socket connections to ports 1024 or greater in its own domain without a policy file.</li>
<li>HTTP policy files may no longer be used to authorize socket connections. Prior to version 9,0,115,0, an HTTP policy file, served from the master location of /crossdomain.xml on port 80, could be used to authorize a socket connection to any port 1024 or greater on the same host.</li>
</ul>
</blockquote>
<p>That&#8217;s right. Your socket policy data can&#8217;t live in the sitewide crossdomain.xml file that Apache serves any more.</p>
<blockquote><p>
Flash Player 9,0,115,0 introduces a concept of socket master policy files, which are served from the fixed TCP port number 843.
</p></blockquote>
<blockquote><p>
Socket policy files may be obtained from the same port as a main connection (the socket connection being made by ActionScript, which is authorized by a socket policy file), or from a different port, separate from the main connection. If you opt to serve a socket policy file from the same port as a main connection, the server listening on that port must understand socket policy file requests (which are indicated by a transmission of
<policy-file-request/> from Flash Player), and must respond differently for policy file requests and main connection requests.
</p></blockquote>
<blockquote>
<ul>
<li>When a SWF file attempts to make a socket connection, even to its own domain, Flash Player will first attempt to contact port 843 to see if the host is serving a socket master policy file.</li>
</ul>
</blockquote>
<p>So&#8230; regardless of whether you&#8217;re even using a custom port 843 client, the Flash Player is going to try to hit it. What if your firewall doesn&#8217;t allow/route traffic to sub-1024 ports w/o special configuration? What if you don&#8217;t have the access to bind to a sub-1024 port and can&#8217;t rewrite your other server process to serve the policy data on its port?</p>
<blockquote>
<ul>
<li>Socket meta-policies can only be declared in a socket master policy file. The syntax is the same as for declaring a meta-policy in an URL master policy file, using the &lt;site-control&gt; tag. Socket meta-policies cannot be declared in HTTP response headers, as HTTP is not involved.</li>
</ul>
</blockquote>
<p>This implies that you can&#8217;t even tell apache to listen to port 843 and serve up the data. You HAVE to either maintain a separate server process specifically for the purpose of serving this policy data, or you have to edit the process that SWF&#8217;s are connecting to and make them serve the data..</p>
<p>As of the time of this writing (10 days after moviestar&#8217;s release), they have yet to release <a href='http://www.adobe.com/devnet/flashplayer/articles/socket_policy_files.html'>promised help</a> on how to deploy a solution to these new changes. Granted, the one article they did release explains what needs to be done in high level terms. It was sufficient to help me out. I wrote a server that simply listens on port 843 and spews the required xml. But&#8230; I&#8217;d have really appreciated specific examples, and I suspect plenty of people would appreciate drop-in solutions to the issue.</p>
<p>A 5-minute skeleton implementation (not recommended for production use by any means) written as a PHP cli script might look something like this:</p>
<pre class="brush: php;">
#!/usr/bin/php
&lt;?
/**
 * Ugly Flash socket policy file service. This script must be run as root from
 * the command line. It binds to port 843 on all interfaces and waits
 * indefinitely for connections. When a connection is detected, the script spits
 * out a chunk of xml and disconnects. It can only serve one request at a time,
 * but that shouldn't be much of a problem.
 *
 * One potential problem with this script is that you can easily lock port 843
 * up for an indeterminate amount of time if the script doesn't exit cleanly.
 * The OS should clear the port up for you eventually, but you could be stuck
 * playing the waiting game.
 *
 * This particular version of the script has only been tested very lightly.
 * Deploy at your own peril <img src='http://ammonlauritzen.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  YMMV.
 *
 * - Ammon Lauritzen [12/13/07]
 */

// define the xml policy &quot;file&quot;
$policy_file =
	'&lt;'.'?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?'.'&gt;'.
	'&lt;cross-domain-policy xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:noNamespaceSchemaLocation=&quot;http://www.adobe.com/xml/schemas/PolicyFileSocket.xsd&quot;&gt;'.
        '&lt;allow-access-from domain=&quot;*&quot; to-ports=&quot;*&quot; secure=&quot;false&quot; /&gt;'.
        '&lt;site-control permitted-cross-domain-policies=&quot;master-only&quot; /&gt;'.
	'&lt;/cross-domain-policy&gt;';

// make sure everything launches correctly
if( posix_getuid() != 0 )
	die( &quot;You must run this script as root.\\\n&quot; );

$sock = @socket_create( AF_INET, SOCK_STREAM, SOL_TCP );
if( !$sock )
	die( &quot;Unable to create socket.\\\n&quot; );

$succ = @socket_bind( $sock, &quot;0.0.0.0&quot;, 843 );
if( !$succ )
	die( &quot;Unable to bind to port 843.\\\n&quot; );

$succ = @socket_listen( $sock );
if( !$succ )
	die( &quot;Unable to start listening.\\\n&quot; );

// start serving policies
while( true ) {
	$r = $w = $e = array( $sock );
	if( @socket_select( $r, $w, $e, null ) !== false ) {
		$conn = @socket_accept( $sock );
		if( $conn !== false ) {
			// somebody connected, just dump the xml and close
			socket_write( $conn, $policy_file );
			socket_close( $conn );
		} else {
			echo &quot;socket_accept() failed?\\\n&quot;;
			break;
		}
	} else {
		echo &quot;socket_select() failed?\\\n&quot;;
		break;
	}
}// end: listen forever

// clean up
socket_close( $sock );
?&gt;
</pre>
<p>I&#8217;ll try to make my production version of this a bit more suitable for public consumption and release it as soon as I can.</p>
<p>The random #2048 security errors continue, despite having deployed my port 843 policy xml server. Granted, they happen less than before&#8230; but they still happen. And even when my policy server isn&#8217;t running, the errors aren&#8217;t thrown 100% of the time. This just baffles me. If they were consistent, that would be one thing. But when you get a security error 1 time in 20&#8230; that&#8217;s not security, that&#8217;s not even a lame deterrent. It&#8217;s just incentive to hammer the same port over and over again until something finally gives.</p>
<p>Now, I admit that I could be wrong here&#8230; but I&#8217;ve re-re-read the documentation on these policies a few times now, and cannot find any reason for the behaviors I&#8217;m seeing.</p>
<h3>update</h3>
<p>On April 22nd, 2008, I released a much better, much more reliable version of this daemon. Head <a href='http://ammonlauritzen.com/blog/2008/04/22/flash-policy-service-daemon/'>over there</a> for more details and source code.</p>
]]></content:encoded>
			<wfw:commentRss>http://ammonlauritzen.com/blog/2007/12/13/new-flash-security-policies/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
	</channel>
</rss>
