Murmurhash is a nice and speedy hashing algorithm that is handy for creating hash values based on strings. I use it often as benchmarks suggest it is one of the speedier implementations out there. Murmurhash can create 32-bit or 128-bit outputs.
In PHP, if you are able to install extensions, then you can simply install the murmurhash extension * (see bottom of page for instructions) and be done with it. If you’re on shared hosting, here is an extensionless alternative to produce 32-bit outputs based on the 2nd version of the murmurhash algorithm.
Do note, it is many times slower than the extension implementation, simply because it’s a user-created function. The code itself is relatively efficient and mostly bitshifting anyway. I had to knock this together because I needed murmurhash in a shared hosting environment where installing extensions is not an option.
if(!function_exists('murmurhash')) {
function murmurhash($key,$seed = 0) {
$m = 0x5bd1e995;
$r = 24;
$len = strlen($key);
$h = $seed ^ $len;
$o = 0;
while($len >= 4) {
$k = ord($key[$o]) | (ord($key[$o+1]) << 8) | (ord($key[$o+2]) << 16) | (ord($key[$o+3]) << 24);
$k = ($k * $m) & 4294967295;
$k = ($k ^ ($k >> $r)) & 4294967295;
$k = ($k * $m) & 4294967295;
$h = ($h * $m) & 4294967295;
$h = ($h ^ $k) & 4294967295;
$o += 4;
$len -= 4;
}
$data = substr($key,0 - $len,$len);
switch($len) {
case 3: $h = ($h ^ (ord($data[2]) << 16)) & 4294967295;
case 2: $h = ($h ^ (ord($data[1]) << 8)) & 4294967295;
case 1: $h = ($h ^ (ord($data[0]))) & 4294967295;
$h = ($h * $m) & 4294967295;
};
$h = ($h ^ ($h >> 13)) & 4294967295;
$h = ($h * $m) & 4294967295;
$h = ($h ^ ($h >> 15)) & 4294967295;
return $h;
}
}
$string = 'mytest'
echo murmurhash($string),"\n";
// outputs 2029812915
* More recently that particular link for instructions on how to install the murmurhash extension is no available. Here is the general gist of how to install the extension:
# download and unzip
cd /tmp
curl -o murmurhash.zip "https://codeload.github.com/zircote/php_murmurhash/zip/master"
unzip murmurhash.zip
cd php_murmurhash-master
# configure and make
phpize
./configure
make
make install
# Add extension to your .ini files
echo "extension=murmurhash.so" >> /etc/php5/apache2/php.ini
echo "extension=murmurhash.so" >> /etc/php5/cli/php.ini