Skip to content

Instantly share code, notes, and snippets.

@adhipg
Created September 14, 2011 17:01
Show Gist options
  • Save adhipg/1217103 to your computer and use it in GitHub Desktop.
Save adhipg/1217103 to your computer and use it in GitHub Desktop.
Creating short URLs/hashes
<?php
function getHash( $n = '' ) {
if( $n == '' ) {
$n = rand();
}
$codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$base = strlen($codeset);
$converted = "";
while ($n > 0) {
$converted = substr($codeset, ($n % $base), 1) . $converted;
$n = floor($n/$base);
}
return $converted;
}
function reverseHash( $hash ) {
$n = 0;
$codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for( $i = strlen($hash); $i; $i-- ) {
$n += strpos($codeset, substr($hash, (-1 * ( $i - strlen($hash) ) ), 1 ) )
* pow( strlen($codeset), $i-1 );
}
return $n;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment