Create your own hash in PHP?
Well, I need to save images with unique filenames and store t开发者_高级运维he file names in the database. I used to do MD5 hash and save the image with the filename of value obtained by hash.
However I would like to cut down the unnecessary space usage from 32 characters to 10-12 characters.
I dont want to substr() the obtained md5 hash to 12 characters.
Rather than that is there a way to create a custom hash of 10-12 characters ?
What about using the following function Tempnam
http://php.net/manual/en/function.tempnam.php
"Creates a file with a unique filename, with access permission set to 0600, in the specified directory. If the directory does not exist, tempnam()
may generate a file in the system's temporary directory, and return the name of that. "
You can represent the 128 Bit MD5 hash values with just 16 characters (8 bit per character instead of just 4).
Maybe using CRC32 instead of MD5? It is 8 characters, not 32, but it is nearer to your goal.
PHP's Hash message digest framework provides tons of hash algorithms. Have fun!
To determine each hash's length, see Wikipedia.
CRC32 is 8 ASCII characters long.
I made this simple hash function to create my own hash with custom characters and size
function simple_hash($str, $size=5, $characters='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
$hash_array = array();
$hash = '';
for($i=0;$i<$size;$i++){
$hash_array[$i]=0;
}
for($s=0;$s<strlen($str);$s++){
for($i=0;$i<$size;$i++){
$hash_array[$i]=($hash_array[$i]+ord($str[$s])+$i+$s+$size)%strlen($characters);
}
}
for($i=0;$i<$size;$i++){
$hash .= $characters[$hash_array[$i]];
}
return $hash;
}
How to use:
<?=simple_hash('test')?> // EIMQU
<?=simple_hash('test')?> // EIMQU
<?=simple_hash('test',10)?> // Y26aeimquy
<?=simple_hash('test',10)?> // Y26aeimquy
<?=simple_hash('test',10,'abcdefghijkl')?> // cgkcgkcgkc
<?=simple_hash('test',10,'abcdeABCDE')?> // eDcBaeDcBa
<?=simple_hash('test2')?> // BGLQV
<?=simple_hash('test3')?> // CHMRW
<?=simple_hash('a big string')?> // gsEQ2
<?=simple_hash('Ελληνικά')?> // 0gwM2
<?=simple_hash('Ελληνικα')?> // 5lBR7
精彩评论