Recursively remove/delete a directory in PHP using SPL components

File system management is not the most common use case for PHP, but in writing a command line tool today I was surprised to find that PHP doesn’t have a function to recursively remove a directory (I was expecting at least a flag for rmdir or unlick, but no, nothing).

I did a quick Google search, just to be sure, and found numerous other people asking this same question and a few rather long winded recursive functional solutions floating around.

No being much of functional programming (and also because really there is no excuse for it when PHP has had reasonable OOP and some fantastic stuff in the SPL for a long time now) I knocked together a much cleaner SPL based solution for recursively deleting a directory:

function recursiveRmDir($dir)
{
    $iterator = new RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST);
    foreach ($iterator as $filename => $fileInfo) {
        if ($fileInfo->isDir()) {
            rmdir($filename);
        } else {
            unlink($filename);
        }
    }
}

I’ve obviously not added any checks to ensure that rmdir and unlink are successful, but this would be a simple addition and I really wanted to post this as an example of a nice modern way to use PHP rather than relying on old functional components.

Share

New features in PHP 5.4

The next iteration of 5.4 looks like it’s more focused on cleaning up the language than features.

It appears many of the previously deprecated functions are now, as promised, removed completely. As this article is about features, here is a quick summary of the other changes:

  • Removed: break/continue $var syntax
  • Removed: register_globals, allow_call_time_pass_reference, and register_long_arrays ini options
  • Removed: session_is_registered(), session_registered(), and session_unregister()

This information is based on alpha/beta releases and is subject to change.

Onwards to the new features…

Traits support

PHP 5.4 includes traits which allow reusable groups of methods to be used from any class.

Here is an example:

trait someMethods
{

    public function doSomething() {}

    public function doSomethingElse() {}

}

We can then use the above trait in an class using the use statement:

class someClass extends someParent
{

    use someMethods;

    public function doSomethingLocaly() {}

}

More information about traits can be found in the manual:


Array dereferencing

As PHP has had object dereferencing for ages, this is something that is really long overdue and addresses the inconsistency between object and array return values.

A quick/common example of the existing object dereferencing:

class someClass
{

    private $_someVar;
    private $_someOtherVar;

    public function setSomeVar($value)
    {
        $this->_someVar = $value;
        return $this;
    }

    public function setSomeOtherVar($value)
    {
        $this->_someOtherVar = $value;
        return $this;
    }

}

$class = new someClass();
$class->setSomeVar(1)->setSomeOtherVar(2);

Now we can do the same with arrays, without the current need to assign the array return value to a variable before we can access it’s contents:

class someOtherClass
{

    public function getArray()
    {
        return array(1, 2, 3, 4, 5);
    }

}

$class = new someOtherClass();
$third = $class->getArray()[2];

This is a rather pointless example, but demonstrates the new functionality.

Share

The most awesomest design pattern, ever to exist and that ever will exist!

At my current day job, someone came up with this design pattern and has implemented it in almost every class throughout the entire application, there are probably close to 100 implementations of this “pattern”. I had to post it because it’s just so awesome!

Firstly let’s late a look at the traditional factory method, it’s usually a static method that instantiates 1 or more objects and returns you the object.

class MyClass
{

    public static function factory($some, $params)
    {
        $it = create_some_object($some, $params);
        return $it;
    }

}

Simple and effective.

Behold! The tri-class factory method, 3 times more awesome than the normal factory method!

Firstly create your class as normal:

class MyClass
{
    ...code...
}

Then create a factory class, (you’re thinking, “what???”, but don’t think, just do):

class MyClassFactory
{
    public static $factory = null;
    ...static methods...
}

Note, some very important features, you must have the public static $factory variable, and it must be initialised to null, despite this being the default behaviour of PHP. The methods also follow a very important structure too, but we’ll get to this in a moment.

Finally, the 3rd and final class, the “Factory Impl” class:

class MyClassFactoryImpl
{
    ...non-static methods...
}

Then to put everything together we need to assign an instance of “Factory Impl” to the static $factory variable in the Factory class, this should be down outside of all the object structures, for added coolness:

MyClassFactory::$factory = new MyClassFactoryImpl;

Confused? You should be. But this is just the start of the awesomeness.

Next, you need to implement the factory methods, they should be implemented as normal public methods in the “Factory Impl” class, e.g.

public function getById($id)
{
    return new object($id);
}

For each method you create, you also need a static function to call this method in the factory class:

public static function getById($id)
{
    return self::$factory->getById($id)
}

Repeat for all your factory methods, and you’re done!

I would recommend that to make it as helpful as possible for other developers, make sure you put everything in one file and try and call the file something different from any of the class names you’ve used, this will ensure that they will probably have to use a require_once each time they use it as it’ll confuse most autoloaders.

You should end up with something like this:

class MyClass
{

    public function __construct($id = null) {}

    public function someMethod() {}

    public function someOtherMethod() {}

}

class MyClassFactoryImpl
{

    public function getEmpty()
    {
        return new MyClass;
    }

    public function getById($id)
    {
        return new MyClass($id);
    }

}

class MyClassFactory
{

    public static $factory = null;
   
    public static function getEmpty()
    {
        return self::$factory->getEmpty();
    }

    public static function getById($id)
    {
        return self::$factory->getById($id);
    }

}

MyClassFactory::$factory = new MyClassFactoryImpl;

There is no denying the awesomeness of this pattern, 3 times more objects, 3 times more memory, 3 times bigger stack, 10 times more code, god knows how many times more inefficient, but infinitely more fun! 😀

Next week, stay tuned for the “super god” class!

Share

Web server benchmark PHP – Apache vs Nginx vs Lighttpd

This is a quick benchmark of the 3 major *nix web servers, to see which gives the best performance.

Test system:

Hardware: vps247 cloud VPS node, 512Mb ram.
Software: Ubuntu 10.10 RC (kernel 2.6.35-22), Apache 2.2.16 (mod_php), Nginx 0.7.67 (php-fpm), Lighttpd 1.4.26 (php-cgi), PHP 5.3.3 with Xcache.
Site: LiteMVC 0.1 Hello World.

Test process:

Using ab with 10,000 requests, 10 concurrent requests.
Monitoring load/memory usage with htop.
All web servers with default configuration, 1 site enabled.
All tests were repeated 3 times.

Apache 2.2.16:

Test 1 Test 2 Test 3
Load at start: 0.03
Memory usage at start: 130 Mb
Load average max: 15.88
Memory usage max: 290 Mb
Requests per second: 400.04
Time per request: 2.5 ms
Longest request: 806 ms
Load at start: 0.07
Memory usage at start: 130 Mb
Load average max: 21.73
Memory usage max: 332 Mb
Requests per second: 395.49
Time per request: 2.529 ms
Longest request: 728 ms
Load at start: 0.06
Memory usage at start: 121 Mb
Load average max: 20.95
Memory usage max: 253 Mb
Requests per second: 385.82
Time per request: 2.592 ms
Longest request: 937 ms

Nginx 0.7.67:

Test 1 Test 2 Test 3
Load at start: 0.05
Memory usage at start: 129 Mb
Load average max: 0.77
Memory usage max: 157 Mb
Requests per second: 413.40
Time per request: 2.419 ms
Longest request: 239 ms
Load at start: 0.05
Memory usage at start: 152 Mb
Load average max: 0.93
Memory usage max: 169 Mb
Requests per second: 409.15
Time per request: 2.444 ms
Longest request: 232 ms
Load at start: 0.00
Memory usage at start: 163 Mb
Load average max: 0.61
Memory usage max: 169 Mb
Requests per second: 415.28
Time per request: 2.408 ms
Longest request: 250 ms

Lighttpd 1.4.26:

Test 1 Test 2 Test 3
Load at start: 0.00
Memory usage at start: 115 Mb
Load average max: 0.81
Memory usage max: 139 Mb
Requests per second: 427.92
Time per request: 2.337 ms
Longest request: 120 ms
Load at start: 0.09
Memory usage at start: 136 Mb
Load average max: 0.73
Memory usage max: 143 Mb
Requests per second: 447.10
Time per request: 2.237 ms
Longest request: 111 ms
Load at start: 0.03
Memory usage at start: 140 Mb
Load average max: 0.69
Memory usage max: 159 Mb
Requests per second: 454.13
Time per request: 2.202 ms
Longest request: 178 ms

Conclusions:

Lighttpd was the fastest overall in this test, however what probably stands out the most is the inefficiency of Apache with both server load and memory usage increasing considerably during the test. The reason for this may be down to Apache spawning additional processes when it is receiving a large volume of requests, which results in the higher memory usage. The memory usage with Nginx and Lighttpd increases by a much smaller amount because each of them runs a fixed number of PHP CGI processes (20 in this case).

Apache is definitely the winner in terms of module support and ease of configuration, but I may have a somewhat biased view as I’ve worked with Apache for years. Nginx is probably the hardest to setup and configure, however after switching from PHP-CGI to PHP-FPM this made things easier and it does seam there are more configuration examples floating around on the net than for Lighttpd. Lighttpd is notorious for memory leaks, I’m not sure if this is still an issue with current versions.

Share

Today is a confusing day for 32 bit PHP

As many people probable know, there are some glaring inconsistencies between 32 bit and 64 bit PHP, especially when it comes to large numbers and floats.

For some reason, best known to the PHP developers, 32 bit PHP is limited to the maximum signed 32 bit integer size of 2147483647, while 64 bit PHP uses the 64 bit equivalent of 9223372036854775807. Many languages overcome the 32 bit / 64 bit differences by storing 64 bit ints as 2 32 bit ints to allow the usage of 64 bit integers on 32 bit systems, hence providing complete consistency between the two platforms.

These inconsistencies similarly apply to floating point precession, presumably a float in 32 bit PHP is equivalent to a 32 bit float in C, whereas it appears that in 64 bit PHP it’s actually a double.

Here is a nice example of the inconsistency, today’s unix timestamp in float form:

32 bit:

php > echo (float) 1285200000;
1.2852E+9

64 bit:

php > echo (float) 1285200000;
1285200000

This is an important thing to remember with PHP, despite the fact it is a loosely typed language, they behaviour is equivalent to the C behaviour for the particular architecture of your server.

Share

WordPress Plugin – Final tweaks

The plugin is now pretty much finished, there are certainly other options that could be added such as page summaries via AJAX, custom image sizes for specific preview etc but for now the only thing that is really left to do is to add a quicktag option so that the plugin can be easily used from the post editor.

This is very simple to do, first I have created a hook to add a script file:

[code lang=”php”]add_action(‘admin_print_scripts’, array(&$this, ‘Admin_Script’));[/code]

This script is only loaded within the admin (hence the action is ‘admin_print_scripts’) and it tells WordPress which function to get the script definition.

The Admin_Script function attaches a simple Javascript file to add the quicktag:

[code lang=”php”]/**
* Load admin javascipt file
*
* @return void
*/
function Admin_Script() {
wp_enqueue_script(‘wp-thumbshot-preview’,
plugin_dir_url(__FILE__) . ‘wp-thumbshot-preview.js’,
array(‘quicktags’),
‘0.1’);
}[/code]

It’s fairly obvious what this does, worth noting that quicktags is a prerequisite (so that the quicktags Javascript functions are loaded first).

The Javascript file ‘wp-thumbshot-preview.js’ contains the quicktag definition:

[code lang=”javascript”]edButtons[edButtons.length] =
new edButton(‘preview’,
‘preview’,
‘[preview]’,
‘[/preview]’,
”);[/code]

Now in the code editor there is a ‘preview’ button so that the plugin’s preview tags can be auto completed!

Share

WordPress Plugin – Admin options page

The next step following the database integration is a simple settings page to change the plugin options. This is achieved with another hook to add an item to the menu in the admin area:

[code lang=”php”]add_action(‘admin_menu’, array(&$this, ‘Admin_Menu’));[/code]

This alone doesn’t do anything other than telling WordPress to call the ‘Admin_Menu’ function at the right time, the function then tells WordPress the menu item to add and which page to open via the add_options_page API function:

[code lang=”php”] /**
* Create admin menu settings item
*
* @return void
*/
function Admin_Menu() {
add_options_page(‘Thumbshot Preview Settings’,
‘Thumbshot Preview’,
8,
basename(__FILE__),
array(&$this, ‘Admin_Settings’));
}[/code]

This creates the page link on the menu as ‘Thumbshot Preview’ and informs which file (the current plugin PHP file) and which function to call ‘Admin_Settings’. The number 8 refers to the user level required to access the page, in this case it is only available to the WordPress admin.

The Admin_Settings function simply outputs some HTML and also provides some very basic form validation and obviously also does the database updates. I have copied the styles and layouts from a standard WordPress settings page to ensure my page is consistent with the default styles. Here is the completed function:

[code lang=”php”] /**
* Display the admin setting page
*
* @return void
*/
function Admin_Settings() {
$msg = null;
// If form submitted save options
if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {
// If free mode, very loose validation as most options are not needed
if ($_POST[‘tsp_mode’] == ‘free’) {
update_option(‘WP_Thumbshot_Preview_Mode’, ‘free’);
if (is_numeric($_POST[‘tsp_cid’])) {
update_option(‘WP_Thumbshot_Preview_Cid’, $_POST[‘tsp_cid’]);
}
if (is_numeric($_POST[‘tsp_width’])) {
update_option(‘WP_Thumbshot_Preview_Width’, $_POST[‘tsp_width’]);
}
if (is_numeric($_POST[‘tsp_height’])) {
update_option(‘WP_Thumbshot_Preview_Height’, $_POST[‘tsp_height’]);
}
$msg = ‘Settings saved.’;
}
// For paid mode make sure the cid is numeric or do not save anything
if ($_POST[‘tsp_mode’] == ‘paid’) {
if (is_numeric($_POST[‘tsp_cid’])) {
update_option(‘WP_Thumbshot_Preview_Mode’, ‘paid’);
update_option(‘WP_Thumbshot_Preview_Cid’, $_POST[‘tsp_cid’]);
if (is_numeric($_POST[‘tsp_width’])) {
update_option(‘WP_Thumbshot_Preview_Width’, $_POST[‘tsp_width’]);
}
if (is_numeric($_POST[‘tsp_height’])) {
update_option(‘WP_Thumbshot_Preview_Height’, $_POST[‘tsp_height’]);
}
$msg = ‘Settings saved.’;
} else {
$msg = ‘Please enter a valid user id.’;
}
}
// Refresh options
$this->Populate_Settings();
}
// Display the page HTML, kinda dirty but quick!
echo ‘

Thumbshot Preview Settings

‘.(!is_null($msg) ? ‘

‘.$msg.’

‘ : null).’


If you have a Thumbshots.com account select paid otherwise use the free Thumbshots.org service.
Your Thumbshots.com user id. [Paid service only]
The default preview image width. [Paid service only]
The default preview image height. [Paid service only]

‘;
}[/code]

The validation here isn’t perfect, but it does the job. Considering the simplicity of this plugin it doesn’t really make much sense to spend time making it any more complex than this. It would be nice to use templates for the HTML as well but again as this is a simple plugin it doesn’t really warrant the complexity.

Here is a screen shot of the settings page:

Thumbshots Preview Settings

Note: The functions listed here are used as part of the object defined in my previous post.

Share

WordPress Plugin – Database integration

The next step with the plugin is to add some database integration so the plugin options can be stored in the WordPress database. This is really simple as the API provides funtions for this in the form of the functions add_option, get_option, update_option and delete_option.

To ensure that the database is populated with some defaults, a hook can be added to do this:

[code lang=”php”]register_activation_hook(__FILE__, array(&$this, ‘Activate’));[/code]

[code lang=”php”] /**
* Activation function – adds database settings
*
* @return void
*/
function Activate() {
add_option(‘WP_Thumbshot_Preview_Mode’, ‘free’, ”, ‘yes’);
add_option(‘WP_Thumbshot_Preview_Cid’, ”, ”, ‘yes’);
add_option(‘WP_Thumbshot_Preview_Width’, ‘160’, ”, ‘yes’);
add_option(‘WP_Thumbshot_Preview_Height’, ‘120’, ”, ‘yes’);
}[/code]

This will be triggered when a user installs the plugin and the default options will be saved to the WordPress options database.

I have also added a deactivation hook to clean up the options from the database when the plugin is deactivated:

[code lang=”php”]register_deactivation_hook(__FILE__, array(&$this, ‘Deactivate’));[/code]

[code lang=”php”] /**
* Deactivation function – removes database settings
*
* @return void
*/
function Deactivate() {
delete_option(‘WP_Thumbshot_Preview_Mode’);
delete_option(‘WP_Thumbshot_Preview_Cid’);
delete_option(‘WP_Thumbshot_Preview_Width’);
delete_option(‘WP_Thumbshot_Preview_Height’);
}[/code]

The default options are set to use the free version of Thumbshots, so the plugin instantly works on activation without any changes to the default settings. To complete the database integration I have also added a function to get the default options from the database when the plugin is loaded (this function is run from the constructor):

[code lang=”php”] /**
* Populate settings from WP
*
* @return void
*/
function Populate_Settings() {
// Usage mode (defaults to free if database settings are missing)
if (($mode = get_option(‘WP_Thumbshot_Preview_Mode’)) !== false) {
$this->mode = $mode;
}
// Thumbshots cid for paid mode
if (($cid = get_option(‘WP_Thumbshot_Preview_Cid’)) !== false) {
$this->cid = $cid;
}
// Image width for paid mode
if (($width = get_option(‘WP_Thumbshot_Preview_Width’)) !== false) {
$this->width = $width;
}
// Image height for paid mode
if (($height = get_option(‘WP_Thumbshot_Preview_Height’)) !== false) {
$this->height = $height;
}
}[/code]

Note: The functions listed here are used as part of the object defined in my previous post.

Share

WordPress Plugin – Further deveopment

Now that I have a very simple working plugin it’s time for a little clean up.

Before I start adding addition functions and build additional features in messy procedural style it makes sense at this state to make it object orientated. WordPress continues to support PHP 4.3 and upwards, hence the plugin should also support PHP 4 configurations.

Here is the class made from the original function, variables have been moved to the object’s global scope, the hooks are included in the constructor and the Render() function now contains the regex replacements:

[code lang=”php”]class WP_Thumbshot_Preview {

/**
* Which mode to use, free or paid.
*
* @var string
*/
var $mode = ‘free’;

/**
* The user id (for paid mode).
*
* @var integer
*/
var $cid;

/**
* The image width
*
* @var integer
*/
var $width;

/**
* The image height
*
* @var integer
*/
var $height;

/**
* Constructor
*
* @return void
*/
function WP_Thumbshot_Preview() {
add_filter(‘the_content’, array(&$this, ‘Render’));
}

/**
* Render the content
*
* @param $content string
* @return string
*/
function Render($content) {
// Free mode
if ($this->mode == ‘free’) {
$content = preg_replace(“/\[preview\](.+?)\[\/preview\]/i”,

$1“,
$content);
}
// Paid mode
if ($this->mode == ‘paid’) {
$content = preg_replace(“/\[preview\](.+?)\[\/preview\]/i”,
cid&v=1&w=$this->width&h=$this->height&url=$1\” />
$1“,
$content);
}
return $content;
}
}[/code]

This is much tidier than before 🙂

Now to make everything work all that is required is an instance of the object:

[code lang=”php”]new WP_Thumbshot_Preview();[/code]

Share