RSS 2.0 Feed
Posted on July 19th, 2010 at 07:08 PM by cballou

I have posted a couple of important updates to MongoSession (a PHP MongoDB Session Handler) that I’d like to share with you.

  1. I have removed the secondary indexed id field which should speed up operations as well as reduce the storage requirements. This is most beneficial for larger sites supporting a high rate of concurrent users.
  2. I recently added two boolean constants, FSYNC and SAFE. These two constants are documented on the MongoCollection::update() page and can be turned on to ensure your session data is actually written to the server. Please note that turning these variables on will cause a performance hit to the overall session handling.
  3. Both the garbage collection and session write methods have been updated to perform atomic operations. This was done as a measure to reduce the risk of race conditions as mentioned on the project page.
  4. A bug was fixed in the read method where an extra line of code existed for no reason.
  5. A bug in the garbage collector was fixed. Update previously only updated a single result as opposed to the whole set of matches.

Click here to be taken to the project page.

Questions, comments, forks, and bugfixes are welcome.

Posted on July 19th, 2010 at 07:58 AM by cballou

I’ve got a bone to pick with the Kohana development team. I just wasted a couple hours out of my day adding functionality to their core Validate class only to find that the functionality had already been added in a future revision. All I was looking to do was pass parameters to a custom callback function. I had even documented the entire change and was looking to post a feature request with an included patch. I later came to realize that the version I was using, 3.0.3, was outdated to the point of lacking this seemingly trivial functionality that was included in 3.0.7. So bare with me while I rant on why your framework is losing in the popularity contest. more »

Posted on April 30th, 2010 at 07:06 AM by cballou

There’s not a whole lot of PHP algorithms floating around. Perhaps people just rely upon the SPL. I had a curiosity to find a string sorting algorithm written in PHP and I didn’t find any non array-based solutions. The implementation I came up with this morning implements recursion, passing by reference, and string iteration. It’s worth noting that this is a horribly slow solution. For this reason I’ve included a very concise solution which is an order of magnitude faster as it uses a C implementation of quicksort which generally runs in O(nlogn). To make people aware of quicksort, I have also implemented a solution for string sorting. With that being said, this could be a fun exercise for students. Alternative solutions and runtime analysis are welcome in the comments section.

Version 1 (slow)

Let’s be honest, if I didn’t use a pre-existing algorithm to create a function, odds are it’s going to be slow. This implementation most closely resembles a version of Bubble Sort without comparing apples to apples.

/**
 * A (slow) non-array based solution for sorting strings in PHP.
 *
 * @param	&$s	The string to be sorted
 * @param	$len	The length of the string
 * @param	$curPos	The current position being sorted (default = 0)
 */
function sortString(&$s, $len = 0, $curPos = 0) {
        if ($curPos === $len) return;
        $nextPos = $curPos + 1;
        while ($nextPos < $len) {
                if ($s{$nextPos} < $s{$curPos}) {
                        $tmp = $s{$curPos};
                        $s{$curPos} = $s{$nextPos};
                        $s{$nextPos} = $tmp;
                }
                ++$nextPos;
        }
        sortString($s, $len, $curPos + 1);
}

// example usage prints:
// 1223344789aaaaadddefffffhhhiillllnnoorrsssuuuuwyy
$string = 'ouhlasfuywernhlasdfoulnarfiuyadf1234987234sdfailh';
sortString($string, strlen($string));
echo $string . "\n";

Version 2 – Quicksort Implementation

Although much faster than version 1, even a user defined quicksort implementation in PHP cannot compare to that of sort.

function sortString($s) {
        $left = $right = '';
        $l = strlen($s) - 1;
        if ($l <= 0) return $s;
        $pivot = floor($l/2);
        do {
                if ($l == $pivot) continue;
                if ($s[$l] <= $s[$pivot]) $left .= $s[$l];
                else $right .= $s[$l];
        } while (--$l);
        return sortString($left) . $s[$pivot] . sortString($right);
}

// example usage prints:
// 1223344789aaaaadddefffffhhhiillllnnoorrsssuuuuwyy
$string = 'ouhlasfuywernhlasdfoulnarfiuyadf1234987234sdfailh';
$string = sortString($string);
echo $string . "\n";

Version 3 – Fast and Concise

This version, although utilizing some fairly heavy functions like split and implode, still outperforms both previous solutions. This is due to the fact it utilizes a small subset of PHP core functions. The core PHP functions have heavily optimized implementations which are written directly in C, meaning it’s nearly impossible to get much faster except in small edge cases.

function sortString(&$s) {
	$s = str_split($s);
	sort($s);
	$s = implode($s);
}

// example usage prints:
// 1223344789aaaaadddefffffhhhiillllnnoorrsssuuuuwyy
$string = 'ouhlasfuywernhlasdfoulnarfiuyadf1234987234sdfailh';
sortString($string, strlen($string));
echo $string . "\n";
Posted on April 26th, 2010 at 07:22 AM by cballou

Let’s face it… nobody enjoys spam. A basic PHP contact form is generally susceptible to a massive amount of spam mail. SPF30 is a PHP library which utilizes a number of recommended spambot deterrents in an attempt to reduce form submission spam. SPF30 does not utilize any form of captcha. In addition to spam prevention methods, SPF30 also handles two-way encryption of form data. In other words, your form content cannot be easily sniffed across the wire. This adds a layer of security to your contact forms.

Features

  • The form submission contains a hashed value of a system defined secret key, the current date, and the user’s user agent.
  • The form submission is invalidated in the event the submission timestamp exceeds a specific timeout period (default 1 hour).
  • The form submission is invalidated in the event it was submitted in rapid succession (default 5 seconds).
  • A hidden input honeypot is utilized in an attempt to trick bots into passing data with the field.
  • A hidden hash field is validated against the submission time, user agent, and secret key.
  • A hidden field is sent containing a the array of encrypted fields for decryption to their old field names.
  • Decrypted form fields are written directly back to the POST array, abstracting the encryption from your backend handling.
  • User specified form field names can undergo two-way DES encryption to obfuscate form field names.
  • User submitted form field values can be encrypted on the frontend using a Javascript implementation of DES.
  • The encryption method goes beyond simple DES encryption for the purposes of transporting UTF-8 characters in POST data.

more »

Posted on April 23rd, 2010 at 08:24 AM by cballou

Download The Me Likey WordPress Plugin Now

UPDATED 06.14.10 8:52 pm

  • Fixed an issue with the shortcode handler calling an undefined function, thereby not registering shortcodes properly.
  • Fixed the screenshots on the WordPress Plugins page.

UPDATED 04.28.10 7:00 am

  • Resolved an issue with the admin id META tag.
  • Disabled the app_id parameter in the configuration until a FBML solution is implemented.
  • Added a “default image” option to the admin to be used when no post image exists.
  • Improved the preview mode to switch to a dark background depending on the layout choice.
  • Added comments to the admin options.
  • Modified the HTML namespace parameters to be included by the script, you must now ensure your header.php file uses the language_attributes() function:
<html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes(); ?>>

UPDATED 04.27.10 8:26 pm

A number of feature requests have been fulfilled.

  • An AJAX preview mode is now available in the options for a quick preview of the button.
  • All META tags are now populating correctly.
  • Fixed parameter naming issue with META tags (replaced “name” with “property”)
  • Additional options have been added to the configuration page; height, layout, show faces, and the ability to define your own custom class for the iframe.
  • Fixed the handling for populating the description meta tag. The code now attempts to get the excerpt first, then the first 255 characters of the post, and lastly the blog description as a fallback.
  • A few other minor issues were resolved which I found while implementing feature requests.

UPDATED 04.27.10 8:00 am

A number of issues with the admin options were found which would hinder you from modifying certain default settings. This has been resolved and the .tar.gz file has been updated accordingly. A couple of outstanding issues noted in the comments are being addressed. These issues include associated images not displaying on Facebook, no admin option for toggling between display methods, and the og:description meta tag not populating properly.

It is recommended that you add the following namespace parameters to your theme’s header.php HTML tag:

<!-- DEPRACATED. See code reference above. -->
<html xmlns:og="http://opengraphprotocol.org/schema/" xmlns:fb="http://www.facebook.com/2008/fbml">

I have dabbled with the Facebook Open Graph API for the past few days following f8 and eventually arrived at a full featured plugin for displaying Facebook’s new “Like” button functionality on your WordPress blog. The plugin is chock full of goodies, including:

  • Option of using either the standard or button_count (small) display mode.
  • Customizable width of the iframe containing the button.
  • The first included image of the post will be cropped to 50×50 and included in the user’s Facebook profile. (possibly broken)
  • Customizable placement of the button, which can be either at the top of your post, bottom of your post, or included using the php function me_likey_button(); in your theme files.
  • Ability to include the button within a post using the shortcode (BBCode) tag [like_button].
  • Ability to change the button’s wording to either “like” or “recommend”.
  • Customizable font family, including arial, lucida grande, segoe ui, tahoma, trebuchet ms, and verdana.
  • Ability to change the color scheme of the button to either “light” or “dark”.
  • Ability to enable/disable the button on a per post (or page) basis directly from the add/edit post screen.
  • Automatic inclusion of Open Graph meta tags to ensure your site is fully compliant with Facebook’s new handling.

Download The Me Likey WordPress Plugin Now

The plugin will have an official page shortly. Suggestions and feature requests are appreciated as I want to ensure the plugin is useable by all. For more details regarding Open Graph and meta data requirements, please click here.

Posted on April 12th, 2010 at 08:34 PM by cballou

There are numerous sites for finding available .COM domain names. Generally, these sites will not turn up the kind of results you are actually looking for when trying to find the perfect domain for your startup, personal site, or business. With the following simple snippet of code you will be able to generate a list of all available two word combinations for a supplied list of keywords. It can be ran from the command line and can output a txt file of all matching domains. I hope you find this as useful as I have. more »

Posted on March 25th, 2010 at 03:41 PM by cballou

PHP inherently makes parsing an array of uploaded files more difficult than it needs to be due to the ordering of it’s array indices. Below is a quick example array:

$_FILES['fieldname']['name'][1] 		= 'uploadedfile.jpg';
$_FILES['fieldname']['name'][2] 		= 'uploadedfile2.jpg';
$_FILES['fieldname']['type'][1] 		= 'image/jpeg';
$_FILES['fieldname']['type'][2] 		= 'image/jpeg';
$_FILES['fieldname']['tmp_name'][1] 	= '/tmp/rAnDOmCHaRs';
$_FILES['fieldname']['tmp_name'][2] 	= '/tmp/RANdOmcHArs';
$_FILES['fieldname']['error'][1] 		= 0;
$_FILES['fieldname']['error'][2] 		= 0;
$_FILES['fieldname']['size'][1] 		= 1427;
$_FILES['fieldname']['size'][2] 		= 1576;

To combat this, we could create a function to reassemble the multi-dimensional array so that it is based on index rather than key. This allows for easier iteration of files. Here’s an example of the reindex $_FILES['fieldname'] array: more »

Posted on November 20th, 2009 at 06:57 PM by cballou

Many, if not all, of you have had to deal with creating a secure site login at some point in time. Although there are numerous articles written on the subject it is painstakingly difficult to find useful information from a single source. For this reason I will be discussing various techniques I have used or come across in the past for increasing session security to hinder both session hijacking and brute force password cracking using Rainbow tables or online tools such as GData. I use the word hinder due to the fact no foolproof methods exist for preventing session hijacking or brute force cracking, merely increasing degrees of difficulty. Choose a method wisely based on your site’s current or anticipated traffic, security concerns, and intended site usage. The following examples have been coded using PHP and MySQL. I more than willingly accept comments, suggestions, critiques, and code samples from readers like you as they benefit the community on the whole. more »

Posted on November 11th, 2009 at 05:51 AM by cballou

There are perhaps hundreds if not thousands of articles on obtaining your visitor’s IP address. The majority if these entries will refer to a small subset of global $_SERVER variables (HTTP_X_FORWARDED_FOR, HTTP_CLIENT_IP, and REMOTE_ADDR). Although both fast and simple solutions utilizing nested ternary operations exist, they are generally prone to a fairly large bug. The HTTP_X_FORWARDED_FOR server directive may contain a comma delimited list of IP addresses based upon several proxy hops prior to the client request packet reaching it’s destination.

After scouring the web I came across two sites demonstrating what appears to be the most accurate IP retrieval method I have come across. I found a number of inefficiencies in the two functions so I’m going to provide you with my optimized version. more »

Posted on May 6th, 2009 at 08:01 PM by cballou

I wanted to share a very quick snippet of code I conjured up to demonstrate the use of Kohana’s validation library to verify the proper size of an uploaded image submitted from form input. The height and width class vars specify the height/width or max height/max width of the image in pixels depending on the boolean value of EXACT_SIZE. If EXACT_SIZE is false, we assume that both the height and width of the uploaded image must be less than or equal to the two constant sizes. more »